Spring 动态设置缓存过期时间 - Caffeine

Spring cache set expire time dinamically - Caffeine

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

您可以设置一个per-entry policy来评估条目并确定到期时间。由于令牌不会在缓存中被修改,您可以使用 expireAfterCreate 并让其他方法 return 和 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));

通过设置自定义Expiry实例,我们可以在每个条目级别设置到期时间。

示例

Cache<Integer, Employee> cache = Caffeine.newBuilder().expireAfter(new Expiry<Integer, Employee>() {
    @Override
    public long expireAfterCreate(Integer key, Employee emp, long currentTime) {
        return TimeUnit.SECONDS.toNanos(emp.getExpiryTime());
    }

    @Override
    public long expireAfterUpdate(Integer key, Employee emp, long currentTime, long currentDuration) {
        return currentDuration;
    }

    @Override
    public long expireAfterRead(Integer key, Employee emp, long currentTime, long currentDuration) {
        return currentDuration;
    }
}).build();

引用link

private static final Expiry<Object, Item<?>> POLICY = new Expiry<>() {
    @Override
    public long expireAfterCreate(Object key, Item<?> value, long currentTime) {
        return value.expiredAt - currentTime;
    }

    @Override
    public long expireAfterUpdate(Object key, Item<?> value, long currentTime, @NonNegative long currentDuration) {
        return currentDuration;
    }

    @Override
    public long expireAfterRead(Object key, Item<?> value, long currentTime, @NonNegative long currentDuration) {
        return currentDuration;
    }
};

Cache<Key, Item<Value>> cache = Caffeine.newBuilder().expireAfter(POLICY).build();

private static class Item<V> {
    private final V value;
    private final long expiredAt;

    Item(final V value, final long ttlMs) {
        this.value = value;
        this.expiredAt = Ticker.systemTicker().read() + TimeUnit.MILLISECONDS.toNanos(ttlMs);
    }
}