Jackson2JsonRedisSerializer
使用Jackson2JsonRedisSerializer缓存数据到redis,获取时出现的异常
需要配置Jackson2JsonRedisSerializer
// 配置Jackson2JsonRedisSerializer // 避免出现获取缓存时出现的类型转换错误 private Jackson2JsonRedisSerializer
该方法参考于https://www.codeprj.com/blog/b1f3f91.html
RedisTemplate
@Bean @ConditionalOnMissingBean( name = {"redisTemplate"} ) public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer jackson2RedisSerializer = jackson2JsonRedisSerializer(); //默认使用jdk序列化, template.setDefaultSerializer(jackson2RedisSerializer); return template; }
RedisCacheManager
// //重写 RedisCacheConfiguration 类的cacheManager方法 并注入IOC容器 @Primary // 设置为默认缓存管理器 @Bean public CacheManager cacheManager(RedisConnectionFactory factory){ Jackson2JsonRedisSerializer jsonRedisSerializer = jackson2JsonRedisSerializer(); RedisCacheConfiguration cacheManager = RedisCacheConfiguration.defaultCacheConfig() //设置缓存有效时间(1小时) .entryTtl(Duration.ofHours(1)) //不缓存null结果,若出现null结果时会报异常 .disableCachingNullValues() //以json形式序列化对象 .serializevaluesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonRedisSerializer)); return RedisCacheManager.builder(factory).cacheDefaults(cacheManager).build(); }