SpringBoot2.3.2版本在redis处理保存json格式的数据的时候,遇到到的坑
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot2.3.2版本在redis处理保存json格式的数据的时候,遇到到的坑相关的知识,希望对你有一定的参考价值。
1.如果我们在容器中使用自己编写的CacheManager,代码如下(注意加粗部分的代码):
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisSerializer<String> strSerialize = new StringRedisSerializer();
Jackson2JsonRedisSerializer<Object> 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);
RedisSerializationContext.SerializationPair<Object> serializationPair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer) ;
RedisSerializationContext.SerializationPair<String> strSerializePair = RedisSerializationContext.SerializationPair.fromSerializer(strSerialize) ;
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
** redisCacheConfiguration.serializeValuesWith(serializationPair);
redisCacheConfiguration.serializeKeysWith(strSerializePair);
redisCacheConfiguration.entryTtl(Duration.ofSeconds(100));// 设置默认超时时间为
redisCacheConfiguration.disableCachingNullValues();**
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration);
return builder.build();
}
采用这种方式保存数据到缓存中的话,数据为jdk序列化之后的数据,并非json格式的数据。
2.如果我们要想保存json格式的数据的话,则我们必须采用链式书写的方式,来进行数据的保存。
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisSerializer<String> strSerialize = new StringRedisSerializer();
Jackson2JsonRedisSerializer<Object> 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);
RedisSerializationContext.SerializationPair<Object> serializationPair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer) ;
RedisSerializationContext.SerializationPair<String> strSerializePair = RedisSerializationContext.SerializationPair.fromSerializer(strSerialize) ;
** RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(serializationPair)
.serializeKeysWith(strSerializePair)
.entryTtl(Duration.ofSeconds(100))// 设置默认超时时间为
.disableCachingNullValues();**
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration);
return builder.build();
}
以上是关于SpringBoot2.3.2版本在redis处理保存json格式的数据的时候,遇到到的坑的主要内容,如果未能解决你的问题,请参考以下文章
linux上redis升级(将 Redis 3.0.7 升级到 5.0.0版本)