码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot2.x配置JsonRedisSerializer

时间:2019-01-21 16:04:12      阅读:532      评论:0      收藏:0      [点我收藏+]

标签:name   config   xcache   template   iss   ring   redist   乱码   oms   

@Configurationpublic class SpringCacheRedisConfig {
   
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(timeToLive)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }

//给redisTemplate配置json序列化
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setDefaultSerializer(RedisSerializer.json());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
} 链接:https://www.jianshu.com/p/9de4d4932e07

这样就可以解决,使用redisTemplate或redisCacheManager操作k-v,导致key:\x0\x0\x00\x000\key,value:乱码
比如:
Order order = orderMapper.selectOrderByOrderId(Long.parseLong(id));
redisTemplate.opsForValue().set("testbrx",order);//
redisTemplate1.opsForValue().set("asda",order);
System.out.println(redisTemplate1.opsForValue().get("asda"));
Cache cache = xcacheManager.getCache("h::1");
if (cache!=null) {
System.out.println(cache.getName());
cache.put("2","asdasdasdasd");
System.out.println(cache.get("2",String.class));
cache.put("3",order);
System.out.println(cache.get("3",Order.class));
}

 

SpringBoot2.x配置JsonRedisSerializer

标签:name   config   xcache   template   iss   ring   redist   乱码   oms   

原文地址:https://www.cnblogs.com/brxHqs/p/10298233.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!