欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot2.x版本自定义CacheManager

程序员文章站 2022-04-30 17:15:36
...

引入了redis的starter后,cacheManager变为 RedisCacheManager(缓存放入redis中);默认创建的 RedisCacheManager 操作redis的时候使用的是 RedisTemplate<Object,Object>,RedisTemplate<Object, Object> 是默认使用jdk的序列化机制,如果需要保存为 json 需要自定义CacheManager

//声明缓存有效时间参数;
private Duration timeToLive = Duration.ofHours(2);//两小时(毫秒)
//声明pojo方法,类上使用了@ConfigurationProperties注解,可以在全局配置文件中设置缓存有效时间
public void setTimeToLive(Duration timeToLive) {
    this.timeToLive = timeToLive;
}
//自定义CacheManager
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {

    RedisSerializer<String> 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))//设置key的序列化规则
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))//设置value的序列化规则
            .disableCachingNullValues();

    RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .build();
    return cacheManager;
}