解决Spring Boot使用RedisTemplate存储键值出现乱码

最近使用spring-data-redis的RedisTemplate操作redis时发现存储在redis中的key不是设置的string值,前面还多出了许多类似\xac\xed\x00\x05t\x00的乱码问题
[redis@k8smaster src]$ ./redis-cli -c  -h 192.168.23.100 -p 3333 -a 123456
192.168.23.100:3333> keys *
1) "\xac\xed\x00\x05t\x00\x14max_app_inst_id_topo"
2) "\xac\xed\x00\x05t\x00\btopo_142"
3) "\xac\xed\x00\x05t\x00\x14serStatusForTopo_142"
4) "\xac\xed\x00\x05t\x00\x0bservice_271"
192.168.23.100:3333> 

spring-data-redis的RedisTemplate模板类在操作redis时默认使用JdkSerializationRedisSerializer来进行序列化,修成使用Jackson2JsonRedisSerialize替换默认序列化可解决乱码问题,代码如下:
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate 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);

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

你可能感兴趣的:(redis)