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?