Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expiry time @cacheable spring boot

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") 
like image 308
nole Avatar asked Jan 15 '15 16:01

nole


People also ask

How to set expire time in cache in spring Boot?

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.

What is the default cache in spring boot?

Spring provides one concurrent hashmap as default cache, but we can override CacheManager to register external cache providers as well easily.

What is EhCache used for?

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.


2 Answers

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()));         }     } 
like image 179
Atum Avatar answered Sep 21 '22 07:09

Atum


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> 
like image 23
Steve Avatar answered Sep 18 '22 07:09

Steve