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

在自义定cacheManager方面,Spring Boot2.X 与Spring Boot1.X 有很大不同,

Spring Boot2 用的是Spring Boot2.X 自定义Redis的cacheManager,保存Json格式到Redis_第1张图片

 按照它的样子,你也可以自定义一个cacheManager,

@Configuration
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisCacheConfig {

    private Duration timeToLive = Duration.ZERO;
    public void setTimeToLive(Duration timeToLive) {
        this.timeToLive = timeToLive;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer 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;
    }

}
spring:
  cache:
    redis:
      timeToLive: 1000000 #毫秒

 这样操作缓存会直接把对象转换成Json格式。

Spring Boot2.X 自定义Redis的cacheManager,保存Json格式到Redis_第2张图片

 

 

你可能感兴趣的:(j2ee,redis,springboot)