欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springboot中redisTemplate乱码或json转换问题

程序员文章站 2022-03-20 08:22:17
...

问题1

用RedisTemplate存入map值的时候,用rdm可视化打开,看到的是转码之后的数据,如图:

Springboot中redisTemplate乱码或json转换问题

存入的方法为:

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字符串取出来后不能转换错误

Springboot中redisTemplate乱码或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转换问题