Весенний тайм-аут установлен динамически - кофеин

Я использую API аутентификации для получения токена и использования других сервисов. Этот API возвращает токен и время истечения. Можно получить время истечения, которое он возвращает, и установить expire_after_write с этими значениями? В настоящее время это свойство находится в application.properties, но я боюсь, что когда-нибудь поставщик услуг изменит expire_time, и мы получим некоторые ошибки, поскольку токен истек

3 ответа

Решение

Вы можете установить политику для каждой записи, чтобы оценить запись и определить срок действия. Поскольку токен не будет изменен в кеше, вы можете использовать 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));

By setting custom Expiry instance, we can set the expiry time at each entry level.

Example

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

Reference 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);
    }
}
Другие вопросы по тегам