如何以编程方式更改 EhCache 成员的到期时间

jef*_*ter 4 java ehcache

我想通过Java代码更改EhCache成员的到期时间或设置到期时间。

我知道对象应该何时到期,但我不确定如何实现。

我知道我可以为整个缓存设置它,例如

Cache cache = manager.getCache("sampleCache");
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToIdleSeconds(60);
config.setTimeToLiveSeconds(120);
config.setMaxEntriesLocalHeap(10000);
config.setMaxEntriesLocalDisk(1000000);
Run Code Online (Sandbox Code Playgroud)

有人可以建议我如何为特定成员执行此操作吗?

Lou*_*met 5

在 Ehcache 2.x 中,您可以在Element插入缓存时设置到期时间:

Element element = new Element("key1", "value1");
element.setTimeToLive(300);
Run Code Online (Sandbox Code Playgroud)

在 Ehcache 3.x 中,您可以实现自定义ExpiryDuration根据key和返回不同的值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);
}
Run Code Online (Sandbox Code Playgroud)

查看API 文档以获取更多信息。