使用Redis資料庫(2)(三十四)
阿新 • • 發佈:2019-01-08
除了String型別,實戰中我們還經常會在Redis中儲存物件,這時候我們就會想是否可以使用類似RedisTemplate<String, User>
來初始化並進行操作。但是Spring Boot並不支援直接使用,需要我們自己實現RedisSerializer<T>
介面來對傳入物件進行序列化和反序列化,下面我們通過一個例項來完成物件的讀寫操作。
- 建立要儲存的物件:User
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public
class
User
implements
Serializable {
private
static
final
long
serialVersionUID = -1L;
private
String username;
private
Integer age;
public
User(String username, Integer age) {
this
.username = username;
this
.age = age;
}
// 省略getter和setter
}
- 實現物件的序列化介面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public
class
RedisObjectSerializer
implements
RedisSerializer<Object> {
private
Converter<Object,
byte
[]> serializer =
new
SerializingConverter();
private
Converter<
byte
[], Object> deserializer =
new
DeserializingConverter();
static
final
byte
[] EMPTY_ARRAY =
new
byte
[
0
];
public
Object deserialize(
byte
[] bytes) {
if
(isEmpty(bytes)) {
return
null
;
}
try
{
return
deserializer.convert(bytes);
}
catch
(Exception ex) {
throw
new
SerializationException(
"Cannot deserialize"
, ex);
}
}
public
byte
[] serialize(Object object) {
if
(object ==
null
) {
return
EMPTY_ARRAY;
}
try
{
return
serializer.convert(object);
}
catch
(Exception ex) {
return
EMPTY_ARRAY;
}
}
private
boolean
isEmpty(
byte
[] data) {
return
(data ==
null
|| data.length ==
0
);
}
}
- 配置針對User的RedisTemplate例項
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @Configuration
public
class
RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return
new
JedisConnectionFactory();
}
@Bean
public
RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, User> template =
new
RedisTemplate<String, User>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(
new
StringRedisSerializer());
template.setValueSerializer(
new
RedisObjectSerializer());
return
template;
}
}
- 完成了配置工作後,編寫測試用例實驗效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 @RunWith
(SpringJUnit4ClassRunner.
class
)
@SpringApplicationConfiguration
(Application.
class
)
public
class
ApplicationTests {
@Autowired
private
RedisTemplate<String, User> redisTemplate;
@Test
public
void
test()
throws
Exception {
// 儲存物件
User user =
new
User(
"超人"
,
20
);
redisTemplate.opsForValue().set(user.getUsername(), user);
user =
new
User(
"蝙蝠俠"
,
30
);
redisTemplate.opsForValue().set(user.getUsername(), user);
user =
new
User(
"蜘蛛俠"
,
40
);
redisTemplate.opsForValue().set(user.getUsername(), user);
Assert.assertEquals(
20
, redisTemplate.opsForValue().get(
"超人"
).getAge().longValue());
Assert.assertEquals(
30
, redisTemplate.opsForValue().get(
"蝙蝠俠"
).getAge().longValue());
Assert.assertEquals(
40
, redisTemplate.opsForValue().get(
"蜘蛛俠"
).getAge().longValue());
}
}
當然spring-data-redis中提供的資料操作遠不止這些,本文僅作為在Spring Boot中使用redis時的配置參考,更多對於redis的操作使用,請參考Spring-data-redis Reference。