SpringBoot2.x配置JsonRedisSerializer
Posted brx_blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot2.x配置JsonRedisSerializer相关的知识,希望对你有一定的参考价值。
@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:x0x0x00x000key,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的主要内容,如果未能解决你的问题,请参考以下文章