Redis - Multiple caches with different TTL

56 views Asked by At

I'm working with Java 17 / Spring and this application.yml is working well. The problem is I need a different time-to-live for each cache:

10s for cache1

20s for cache2

spring:
  cache:
    cache-names: cache1, cache2
    type: redis
    redis:
      time-to-live: 10s
      key-prefix: rop
      use-key-prefix: true
      cache-null-values: false
      enable-transaction-support: false
  data:
    redis:
      url:redis://localhost:6379

I already tried some variations of this file, but none worked. any clue? Thanks in advance!

1

There are 1 answers

1
Alexandre Mateus On

I've found an solution at this link

Here is the code that help me out:

@Bean (name="cacheManager")
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheConfiguration conf_1_info = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(10));

    RedisCacheConfiguration conf_2_info = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(30));

    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<String, RedisCacheConfiguration>();
    cacheConfigurations.put("cache1", conf_1_info);
    cacheConfigurations.put("cache2", conf_2_info);

    return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory)
            .withInitialCacheConfigurations(cacheConfigurations).build();
}