I would like to change the expiry or set the expiry time of a member of an EhCache via Java code.
I know when the object should expire, but I'm unsure how to achieve this.
I know I can set it for the whole cache, e.g.
Cache cache = manager.getCache("sampleCache");
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToIdleSeconds(60);
config.setTimeToLiveSeconds(120);
config.setMaxEntriesLocalHeap(10000);
config.setMaxEntriesLocalDisk(1000000);
Can someone suggest how I do this for a specific member?
In Ehcache 2.x, you can set expiry time on the Element
you insert in the cache:
Element element = new Element("key1", "value1");
element.setTimeToLive(300);
In Ehcache 3.x, you can implement a custom Expiry
and have it return different Duration
depending on the key
and value
:
public interface Expiry<K, V> {
Duration getExpiryForCreation(K key, V value);
Duration getExpiryForAccess(K key, ValueSupplier<? extends V> value);
Duration getExpiryForUpdate(K key, ValueSupplier<? extends V> oldValue, V newValue);
}
Check the API documentation for more information.