Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

java - 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.

question from:https://stackoverflow.com/questions/65848654/set-ttl-fot-caching-different-data-with-one-cachemanager-in-spring-boot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...