how to configure different ttl for each redis cache when using @cacheable in springboot2.0

后端 未结 3 440

I am using @cacheable in springboot2.0 with redis. I have configured RedisCacheManager as follow:

@Bean
public RedisCacheManager redisCacheManager(RedisConne         


        
3条回答
  •  再見小時候
    2021-01-06 06:18

    You can configure different expire time for each cache using only one CacheManager by creating different configurations for each cache and put them in a map with which you create the CacheManager.

    For example:

    @Bean
    RedisCacheWriter redisCacheWriter() {
        return RedisCacheWriter.lockingRedisCacheWriter(jedisConnectionFactory());
    }
    
    @Bean
    RedisCacheConfiguration defaultRedisCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(defaultCacheExpiration));
    }
    
    @Bean
    CacheManager cacheManager() {
        Map cacheNamesConfigurationMap = new HashMap<>();
        cacheNamesConfigurationMap.put("cacheName1", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl1)));
        cacheNamesConfigurationMap.put("cacheName2", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl2)));
        cacheNamesConfigurationMap.put("cacheName3", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(ttl3)));
    
        return new RedisCacheManager(redisCacheWriter(), defaultRedisCacheConfiguration(), cacheNamesConfigurationMap);
    }
    

提交回复
热议问题