简体   繁体   中英

Can i expire a spring cache without using ehcache

I have been trying to use spring cache which comes with spring context. It is running fine without using ehcache, as given in this example:

https://github.com/michaelisvy/proxy-samples/tree/master/src/main/java/cache/simple

Now I want the cache stored to expire after 5 minutes . A lot of examples are using ehcache for this. Can I do this without using ehcache and with only the spring cache?

As per the documentation, you need to have a library that supports that rather than just an abstraction (which you are doing currently).

Reference Guide - How can I set the TTL/TTI/Eviction policy/XXX feature?

Other option would be to use Guava along with spring. Look at the example here - Spring 3.1 and Guava 1.13.1 to set CacheTTL

If you're talking about org.springframework.cache.concurrent.ConcurrentMapCache that comes with Spring, it's not possible. It simply uses java.util.concurrent.ConcurrentHashMap as a cache store. However, you can create scheduler to remove the cache manually. If you want to go that route, you have to create the object that holds timestamp information.

class CacheElement {
  long timestamp;
  Object value;
  public CacheElement(Object value){
     this.value = value;
     touch();
  }
  public void touch(){
     this.timestamp = new Date().getTime();
  }
  ..../omit for breifvity
}

You have to wrap the cache value with CacheElement as defined above and you have to override the org.springframework.cache.Cache.ValueWrapper#get to call touch() before returning value. Also, you may want to check whether the cache value already expires. Compare timestamp in CacheElement with current timestamp if it's less than specified TTL, touch() it. Otherwise, remove from cache store and return null.

Hope you got the idea :)

My suggestion, use ehcache or other libraries that support TTL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM