Spring Boot Spring Boot 2.x 版本 CacheManager 配置方式

Posted 【一粒大米】洞悉技术的本质,享受科技的乐趣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot Spring Boot 2.x 版本 CacheManager 配置方式相关的知识,希望对你有一定的参考价值。

Spring Boot 1.X RedisCacheManager 配置方式

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager= new RedisCacheManager(redisTemplate);
    cacheManager.setDefaultExpiration(60);
    Map<String,Long> expiresMap=new HashMap<>();
    expiresMap.put("Product",5L);
    cacheManager.setExpires(expiresMap);
    return cacheManager;
}

Spring Boot 2.X RedisCacheManager 配置方式

  /**
     * SpringBoot 2.X 版本配置方式
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        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);
        CacheKeyPrefix keyPrefix = new CacheKeyPrefix() {
            @Override
            public String compute(String cacheName) {
                return cacheName + "::";
            }
        };
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
          //失效时间 .entryTtl(Duration.ofMinutes(
3)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); return RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(config) .build(); }

 

以上是关于Spring Boot Spring Boot 2.x 版本 CacheManager 配置方式的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 2:Spring Boot 2.0新特性

Spring boot- Spring Boot特性2

Spring Boot学习总结(29)—— Spring Boot 2.6 新特性

Spring Boot学习总结(29)—— Spring Boot 2.6 新特性

Spring-Boot Banner

Spring Boot:管理的版本是 1.3.2.RELEASE 工件在 org.springframework.boot:spring-boot-dependencies:1.3.2.RELEASE