Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set TTL fot caching different data with one CacheManager in Spring Boot

I am caching responses from three different external sources and I am using same CacheManager. I would like to set different TTL for each method, that is cached, is it possible?

I also tried to set up multiple cache managers, but I got and exception - 2 implementations of CachingConfigurer were found when only 1 was expected

Here is my CacheConfig class with my CacheManager - this is where I have my config for my manager

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    private static final String CACHE_NAME = "transportLocations";

    // Here is "global" TTL for every result from the method
    private static final int TTL_SECONDS = 15;
    private static final int ENTRIES_LOCAL_HEAP = 1000;
    private static final String LRU = "LRU";

    @Bean
    public net.sf.ehcache.CacheManager ehCacheManager() {
        final var transportLocationCache = new CacheConfiguration();
        final var config = new net.sf.ehcache.config.Configuration();

        transportLocationCache.setName(CACHE_NAME);
        transportLocationCache.setMaxEntriesLocalHeap(ENTRIES_LOCAL_HEAP);
        transportLocationCache.setMemoryStoreEvictionPolicy(LRU);
        transportLocationCache.setTimeToLiveSeconds(TTL_SECONDS);
        config.addCache(transportLocationCache);

        return net.sf.ehcache.CacheManager.newInstance(config);
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }
}

This is my service, where I am using Cacheable annotation. I have three methods where I am using this annotation and this is where I need to set different TTL for every method.

@Cacheable(value = TRANSPORT_LOCATIONS, cacheManager = CACHE_MANAGER, key = ROOT_METHOD_NAME, sync = true)

Do you have any suggestions, how to do that?

Thank you very much.

like image 543
Petr Jelínek Avatar asked Oct 22 '25 04:10

Petr Jelínek


2 Answers

I used multiple cache managers combined with cache resolver. I followed these tutorials.

https://www.baeldung.com/spring-multiple-cache-managers

https://www.baeldung.com/spring-boot-caffeine-cache

like image 87
Petr Jelínek Avatar answered Oct 23 '25 17:10

Petr Jelínek


In order to use cache-specific TTL, you don't have to use different cache managers. While EhCache and some other cache providers give you the possibility to configure that using dedicated XML, for in-memory providers you may need to configure each cache along with the CacheManager.

Please see http://dolszewski.com/spring/multiple-ttl-caches-in-spring-boot/ for more details.

like image 28
Aleksandar Radulović Avatar answered Oct 23 '25 17:10

Aleksandar Radulović