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

4

8

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

@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {

    RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
    SerializationPair<Object> valueSerializationPair = RedisSerializationContext.SerializationPair
            .fromSerializer(new GenericJackson2JsonRedisSerializer());
    RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
    cacheConfiguration = cacheConfiguration.serializeValuesWith(valueSerializationPair);
    cacheConfiguration = cacheConfiguration.prefixKeysWith("myPrefix");
    cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));

    RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter, cacheConfiguration);
    return redisCacheManager;
}

but this make all key's ttl 30 second, how to configure different ttl for each redis cache with different cachename?

Victoir answered 27/6, 2018 at 4:56 Comment(2)
i think i have figured it out by configure different RedisCacheManager with different bean name. Everythings looks good for nowVictoir
@c-y-in-sof you can answer your own questionNapiform
V
4

If you need configure different expire time for cache when using @cacheable , you can configure different CacheManager with different ttl,and specify cacheManager when using cache in your service.

 @Cacheable(cacheManager = "expireOneHour", value = "onehour", key = "'_onehour_'+#key", sync = true)
Victoir answered 2/7, 2018 at 4:56 Comment(0)
B
21

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<String, RedisCacheConfiguration> 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);
}
Boito answered 25/9, 2018 at 9:7 Comment(1)
I think this is the right answer instead of the marked answerJozef
V
4

If you need configure different expire time for cache when using @cacheable , you can configure different CacheManager with different ttl,and specify cacheManager when using cache in your service.

 @Cacheable(cacheManager = "expireOneHour", value = "onehour", key = "'_onehour_'+#key", sync = true)
Victoir answered 2/7, 2018 at 4:56 Comment(0)
R
0

Here is how you can define multiple Redis based caches with different TTL and maxIdleTime using Redisson Java client:

    @Bean(destroyMethod="shutdown")
    RedissonClient redisson() throws IOException {
        Config config = new Config();
        config.useClusterServers()
              .addNodeAddress("redis://127.0.0.1:7004", "redis://127.0.0.1:7001");
        return Redisson.create(config);
    }

    @Bean
    CacheManager cacheManager(RedissonClient redissonClient) {
        Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();

        // create "myCache1" cache with ttl = 20 minutes and maxIdleTime = 12 minutes
        config.put("myCache", new CacheConfig(24*60*1000, 12*60*1000));

        // create "myCache2" cache with ttl = 35 minutes and maxIdleTime = 24 minutes
        config.put("myCache2", new CacheConfig(35*60*1000, 24*60*1000));
        return new RedissonSpringCacheManager(redissonClient, config);
    }
Roos answered 6/3, 2020 at 9:30 Comment(0)
B
0

This is my code:

  1. The shared config in common module

     @Bean
     RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer(List<RedisTtlConfig> ttlConfigs) {
         RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
         return (builder) -> {
             Map<String, RedisCacheConfiguration> ttlConfigMap = new HashMap<>();
             ttlConfigs.forEach( config -> {
                 config.forEach( (key, ttl) -> {
                     ttlConfigMap.put(key, defaultCacheConfig.entryTtl(Duration.ofSeconds(ttl)));
                 });
             });
             builder.withInitialCacheConfigurations(ttlConfigMap);
             builder.cacheDefaults(defaultCacheConfig);
         };
     }
    
  2. A custom class to collect ttl config by key

     public class RedisTtlConfig extends HashMap<String, Long> {
    
         public RedisTtlConfig setTTL(String key, Long ttl){
             this.put(key, ttl);
             return this;
         }
     }
    

3.Simple ttl config code in ref module

    @Bean
    RedisTtlConfig corpCacheTtlConfig(){
        return new RedisTtlConfig()
                .setTTL("test1", 300l)
                .setTTL("test2", 300l);
    }
Bias answered 9/2, 2023 at 4:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.