Spring Boot2.X 自定义Redis的cacheManager,保存Json格式到Redis

匿名 (未验证) 提交于 2019-12-03 00:44:02

https://blog.csdn.net/caojidasabi/article/details/83059642

配置好自定义RedisCacheManager 组件,就可以自动将要保存的数据以JSON格式存入Redis
 1 @Configuration  2 public class MyRedisConfig {  3   4     @Bean  5     public RedisCacheManager cacheManager(RedisConnectionFactory factory) {  6   7         RedisSerializer<String> redisSerializer = new StringRedisSerializer();  8         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);  9  10         //解决查询缓存转换异常的问题 11         ObjectMapper om = new ObjectMapper(); 12         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 13         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 14         jackson2JsonRedisSerializer.setObjectMapper(om); 15  16         //配置序列化(解决乱码的问题) 17         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() 18                 .entryTtl(Duration.ZERO) 19                 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) 20                 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) 21                 .disableCachingNullValues(); 22  23         RedisCacheManager cacheManager = RedisCacheManager.builder(factory) 24                 .cacheDefaults(config) 25                 .build(); 26         return cacheManager; 27     } 28 }

来源: https://www.cnblogs.com/hcklqy/p/11355687.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!