更改 EHCache 3 中单个条目的 TTL
Changing the TTL of individual entries in EHCache 3
在 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 and 后,我觉得此功能不能直接迁移。
指南告诉我们,为了修改 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?
仅当条目被创建、访问或更新时才能修改过期期限.
现在,根据您的具体要求,您可以在 getExpiryForAccess
上实施您的特定逻辑并访问映射以获取更新的到期时间。但是,您无法区分 常规 访问和应该更新过期的访问。
而且我不建议进行这种有状态的过期计算。
可能有其他方法可以通过完全更改缓存设计来支持您的用例,但这不在本问题的讨论范围内。
在 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 and
指南告诉我们,为了修改 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?
仅当条目被创建、访问或更新时才能修改过期期限.
现在,根据您的具体要求,您可以在 getExpiryForAccess
上实施您的特定逻辑并访问映射以获取更新的到期时间。但是,您无法区分 常规 访问和应该更新过期的访问。
而且我不建议进行这种有状态的过期计算。
可能有其他方法可以通过完全更改缓存设计来支持您的用例,但这不在本问题的讨论范围内。