I\'m working with ehcache 2.5.4.
I have an object that needs to be cached through out the day and refreshed with a new value at 00:00am every day.
Currently with
With Ehcache 3.2 I implemented an Expiry extension.
public class EvictAtMidnightExpiry implements Expiry {
@Override
public Duration getExpiryForCreation(Object key, Object value) {
DateTime now = new DateTime();
DateTime resetAt = now.plusDays(1).withTimeAtStartOfDay();
long difference = resetAt.toDateTime().getMillis() - now.getMillis();
return Duration.of(difference, TimeUnit.MILLISECONDS);
}
@Override
public Duration getExpiryForAccess(Object key, ValueSupplier value) {
return null;
}
@Override
public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) {
return null;
}
}
Now, I have logging etc as well but I minimalized my code for cleanness.
Then you just need to configure it in your configuration builder.
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(1000)).withExpiry(new EvictAtMidnightExpiry()).build()
Clearly Ehcache improved on there API's somewhat from 2.5 to 3.2 as you don't need to create your own 'element' and ensure it's usage to initiate expiry or eviction policies. The policies are now cache bound.