Springboot操作Redis时,发现key值出现
\xac\xed\x00\x05t\x00\tb
今天使用Spring Boot Data 操作Redis时,发现key值出现 \xac\xed\x00\x05t\x00\tb
,但不影响程序读写,查询资料发现RedisTemplate
默认的序列化方式为 JdkSerializeable
, StringRedisTemplate
的默认序列化方式为 StringRedisSerializer
话不多说,上解决方案:
其实就是指定序列化的方式,默认是
JdkSerializeable
是以二进制数组方式存储,内容没有可读性。
@Bean(name = "redisTemplateJackson")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean(name = "redisTemplateString")
public RedisTemplate<String, String> getRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
// key的序列化类型
redisTemplate.setKeySerializer(new StringRedisSerializer());
// value的序列化类型
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setDefaultSerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
Jackson2JsonRedisSerializer
效率最高