咖啡因 - 如何仅在创建时间后过期缓存值

Kap*_*lny 0 java caching caffeine

Caffeine 具有expiresAfterWrite查看上次写入时间的方法。我希望它只查看创建时间。因此,当第一个条目出现时,条目将在固定时间后过期,而无需查看此条目的更新次数。这可能吗?

Ben*_*nes 11

可以,但需要使用更高级的Expiryapi。在下面的示例中,新创建的条目具有固定的 5 分钟生命周期。这是通过返回currentDuration更新或读取来完成的。

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));
Run Code Online (Sandbox Code Playgroud)