最近做了一个项目,数据量比较大,所以用到了 @Cacheable注解,嫌麻烦,百度找了相关配置,如下:
序列化配置
@Bean
public static RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
redisConnectionFactory.setValidateConnection(true);//使用前先校验连接,如果不可用就重新连接,而不是直接报错connection reset by peer
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
管理器配置
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
ObjectMapper om = new ObjectMapper();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
Object.class);
// 解决查询缓存转换异常的问题
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMillis(-1))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
return new RedisConfigCacheManager(cacheWriter, config);
}
运行之后正常序列化,反序列化出现问题,报错
Cannot construct instance of
com.vt.common.Result
(no Creators, like
default constructor, exist)
红色部分是我自己的返回结构,问题原因是找不到无参构造方法,谷歌也是显示添加无参构造方法,这个方法确实可以解决问题,推荐使用lombok添加,但是这样麻烦不说,有些时候使用的是第三方包的类或者方法,在给Result添加了无参构造后接着分页方法也报错,也是这个问题,我总不能重写整个分页吧。
后来直接掉CacheManager 管理器的bean注入就好了,另外还有问题的就修改序列化value的配置为JdkSerializationRedisSerializer,黄色部分,估计是CacheManager里面还有些什么反序列化配置没有配置到,求有缘人告知
@Bean
public static RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
redisConnectionFactory.setValidateConnection(true);
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(`new JdkSerializationRedisSerializer()`);
template.setConnectionFactory(redisConnectionFactory);
return template;
}