2

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

4

3 回答 3

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));
于 2018-10-31T19:23:41.503 回答
0

通过设置自定义 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();

参考链接

于 2021-04-28T05:12:26.680 回答
0
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);
    }
}
于 2022-03-03T07:26:31.877 回答