Caffeine - how expires Cached values only after creation time

牧云@^-^@ 提交于 2020-12-15 06:18:45

问题


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?


回答1:


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));


来源:https://stackoverflow.com/questions/51779879/caffeine-how-expires-cached-values-only-after-creation-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!