用RedisTemplate存入map值的时候,用rdm可视化打开,看到的是转码之后的数据,如图:
存入的方法为:
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
log.error(key, e);
return false;
}
}
存入的json字符串取出来后不能转换错误
@Resource
private RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
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);
// 防止乱码
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); //解决json转换
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);//解决哈唏值转换
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
Springboot中redisTemplate乱码或json转换问题
原文:https://www.cnblogs.com/pigmen/p/14096462.html