Springboot中redisTemplate乱码或json转换问题
程序员文章站
2022-03-20 08:22:17
...
问题1
用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;
}
}
问题2
存入的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;
}
上一篇: Mac笔记本如何安装java
下一篇: PHPExcel如何导出excel的方法