咖啡因-仅在创建后如何使缓存的值过期 [英] Caffeine - how expires Cached values only after creation time

查看:64
本文介绍了咖啡因-仅在创建后如何使缓存的值过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

咖啡因具有 expiresAfterWrite 方法,该方法在最后一次写入时间进行查找.我希望它仅在创建时查看.因此,当第一个条目到来时,条目将在固定的时间后过期,而无需查看该条目的更新数量.这可能吗?

Caffeine has expiresAfterWrite method which looks at last write time. I want it to look only at the creation time. So when the first entry comes then entry will be expired after a fixed amount of time without looking at the number of updates on this entry. Is this possible?

推荐答案

是的,但需要使用更高级的 Expiry api.在下面的示例中,新创建的条目的生命周期固定为5分钟.这是通过在更新或读取时返回 currentDuration 来完成的.

Yes, but requires using the more advanced Expiry api. In the below example, a newly created entry has a fixed 5 minute lifetime. This is done by returning currentDuration on an update or read.

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .expireAfter(new Expiry<Key, Graph>() {
      public long expireAfterCreate(Key key, Graph graph, long currentTime) {
        return TimeUnit.MINUTES.toNanos(5);
      }
      public long expireAfterUpdate(Key key, Graph graph, 
          long currentTime, long currentDuration) {
        return currentDuration;
      }
      public long expireAfterRead(Key key, Graph graph,
          long currentTime, long currentDuration) {
        return currentDuration;
      }
    })
    .build(key -> createExpensiveGraph(key));

这篇关于咖啡因-仅在创建后如何使缓存的值过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆