简体   繁体   中英

Guava cache: how to set expiration on 'CacheLoader.load()' instead of during CacheBuilder.newBuilder()?

I am trying to create a cache using guava cache library. One my main requirement is that I want to set the cache expiry after the CacheLoader.load(..) function instead of something most of the examples I encountered on the web, like the one below.

LoadingCache<String, MyClass> myCache = 
CacheBuilder.newBuilder().maximumSize(MAX_SIZE).expireAfterWrite(10, TimeUnit.Minutes).build(cacheLoader);

The reason for this is that the object retrieved from the database by the CacheLoader.load(...) function contains the expiration data. So I want to use this information instead of some "random" static value.

I want something like this.

LoadingCache<String, MyClass> myCache = 
CacheBuilder.newBuilder().maximumSize(MAX_SIZE).build(cacheLoader);

...

CacheLoader meCacheLoder = new CacheLoader<String MyClass>(){
   @Override
   public MyClass load(String key) throws Exception {
      // Retrieve the MyClass object from database using 'key'
      MyClass myObj = getMyObjectFromDb(key);  
      int expiry = myObj.getExpiry();

         // Now somehow set this 'expiry' value with the cache
         ????

      return myObj;
   }
 };

OR Is there any better option available than Guava cache for this purpose?

There is no such feature in Guava, as Louis already pointed out.

For example you can use EHCache or cache2k . For cache2k I can give you quick directions since this is a core feature we use regularly:

You can either implement the interface ValueWithExpiryTime on your value object, which is:

interface ValueWithExpiryTime {

  long getCacheExpiryTime();

}

Or, you can register a EntryExpiryCalculator to extract the time value. The cache is build as follows:

Cache<Key, Value> cache = 
  CacheBuilder.newCache(Key.class, Value.class)
    .expiryCalculator(new EntryExpiryCalculator<Key, Value>() {
        @Override
        public long calculateExpiryTime(
            final Key key, final Value value, 
            final long loadTime, final CacheEntry<Key, Value> oldEntry) {
          return value.getExpiry();
        }
      }
    )
    .build();

The time is the standard long type represented in milliseconds since the epoch. By default the expiry will happen not exactly at the specified time, but zero or a few milliseconds later, depending on your machine load. This is the most effective mode. If this is a problem, add sharpExpiry(true) .

Disclaimer: I am the author of cache2k....

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