Spring 缓存动态设置过期时间 - 咖啡因

ghn*_*712 2 spring-cache caffeine

我使用身份验证 API 来获取令牌并使用其他服务。此 API 返回令牌和过期时间。可以获取它返回的过期时间并使用这些值设置 expire_after_write 吗?目前这个属性在 application.properties 中,但我担心有一天服务提供者改变了 expire_time 并且我们会因为令牌过期而得到一些错误

Ben*_*nes 5

您可以设置每个条目的策略来评估条目并确定到期时间。由于令牌不会在缓存中被修改,您可以使用expireAfterCreate并让其他方法返回currentDuration不修改它。从文档中,

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .expireAfter(new Expiry<Key, Graph>() {
      public long expireAfterCreate(Key key, Graph graph, long currentTime) {
        // Use wall clock time, rather than nanotime, if from an external resource
        long seconds = graph.creationDate().plusHours(5)
            .minus(System.currentTimeMillis(), MILLIS)
            .toEpochSecond();
        return TimeUnit.SECONDS.toNanos(seconds);
      }
      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)