Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 340
C.y in sof Avatar asked Dec 02 '22 10:12

C.y in sof


2 Answers

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);
}
like image 150
Manos Avatar answered Dec 04 '22 00:12

Manos


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)
like image 41
C.y in sof Avatar answered Dec 03 '22 23:12

C.y in sof