【发布时间】:2017-04-10 21:02:01
【问题描述】:
在 EHCache 2.x 中,可以为缓存中的单个条目设置生存时间,例如:
Element dependentElement = cache.get(key);
long lastAccessTime = dependentElement.getLastAccessTime();
long creationTime = dependentElement.getCreationTime();
int timeToLive = lastAccessTime == 0 ? 300 : (int)
(lastAccessTime - creationTime) / 1000 + 300;
timeToLive += 2;
dependentElement.setTimeToLive(timeToLive);
这将更新单个项目的 TTL,从而使其在缓存中的保存时间更长。
在 EHCache 3.x 中,这似乎不再可能在单个缓存条目的基础上进行。在阅读了Migration Guide 和this question 之后,在我看来这个功能是不能直接迁移的。
指南告诉我们,为了修改 TTL,必须实现一个接口:
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class,
String.class, ResourcePoolsBuilder
.withExpiry(new Expiry<Long, String>() {
@Override
public Duration getExpiryForCreation(Long key, String value) {
return getTimeToLiveDuration(key, value);
}
@Override
public Duration getExpiryForAccess(Long key, ValueSupplier<? extends String> value) {
return null; // Keeping the existing expiry
}
@Override
public Duration getExpiryForUpdate(Long key, ValueSupplier<? extends String> oldValue, String newValue) {
return null; // Keeping the existing expiry
}
});
然后将此配置添加到要初始化的缓存中。但是,由于它是缓存级扩展点,您似乎永远无法保证为您要更改的实际条目触发方法?
查看 EHCache 3 的内部结构,似乎旧的 net.sf.ehcache.Element 被抽象出来并变成了一个 ValueHolder
那么,问题是:我们如何在 EHCache 3.x 中实现相同的行为?
【问题讨论】: