指定RedisTemplate的序列化方式
指定序列化方式 fastJsonRedisSerializer
@Configuration
public class RedisConfig {
/**
* redisTemplate 默认的序列化方式为 JdkSerializationRedisSerializer
* StringRedisTemplate 的默认序列化方式为 StringRedisSerializer
* 使用 fastJsonRedisSerializer 替换默认序列化方式
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// 设置值value的序列化方式
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键key的序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
方法
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value, Long time){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}
public Object get(String key){
return redisTemplate.opsForValue().get(key);
}
}
测试
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
void contextLoads() {
redisTemplate.opsForValue().set("user", new UserInfo("admin"));
// UserInfo user = (UserInfo) redisTemplate.opsForValue().get("user");
// 反序列化需要指定类型
Object user = redisTemplate.opsForValue().get("user");
User userInfo = JSONObject.parseObject(JSON.toJSONString(user), User.class);
}