【问题标题】:Changing the TTL of individual entries in EHCache 3更改 EHCache 3 中各个条目的 TTL
【发布时间】: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 中实现相同的行为?

【问题讨论】:

    标签: java ehcache


    【解决方案1】:

    只有在条目被创建、访问或更新时才能修改过期时间。

    现在,根据您的具体要求,您可以在 getExpiryForAccess 上实现您的特定逻辑并访问映射以获取更新的过期时间。但是,您无法区分 常规 访问和应该更新过期的访问。 而且我也不建议进行这种有状态的过期计算。

    可能有其他方法可以通过完全更改缓存设计来支持您的用例,但这超出了本问题的范围。

    【讨论】:

    • 谢谢,我就是这么想的。我们将重新实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多