@Configuration
public 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));
}