I have implemented a cache and now I want to add an expiry time.
How can I set an expiry time in spring boot with @Cacheable
?
This is a code snippet:
@Cacheable(value="forecast",unless="#result == null")
You cannot specify expiry time with @cacheable notation, since @cacheable does not provide any such configurable option. However different caching vendors providing spring caching have provided this feature through their own configurations.
Spring provides one concurrent hashmap as default cache, but we can override CacheManager to register external cache providers as well easily.
Ehcache is a standards-based caching API that is used by Integration Server. Caching enables an application to fetch frequently used data from memory (or other nearby resource) rather than having to retrieve it from a database or other back-end system each time the data is needed.
I use life hacking like this
@Configuration @EnableCaching @EnableScheduling public class CachingConfig { public static final String GAMES = "GAMES"; @Bean public CacheManager cacheManager() { ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(GAMES); return cacheManager; } @CacheEvict(allEntries = true, value = {GAMES}) @Scheduled(fixedDelay = 10 * 60 * 1000 , initialDelay = 500) public void reportCacheEvict() { System.out.println("Flush Cache " + dateFormat.format(new Date())); } }
Note that this answer uses ehcache, which is one of supported Spring Boot cache managers, and arguably one of the most popular.
First you need to add to pom.xml
:
<!-- Spring Framework Caching Support --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency>
In src/main/resources/ehcache.xml
:
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" /> <cache name="forecast" maxElementsInMemory="1000" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" /> </ehcache>
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