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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With