I use an authentication API to get a token and use other services. This API returns the token and expire time. It's possible to get the expire time it returns and set expire_after_write with these value? Currently this property is in application.properties, but I'm afraid that someday the service provider change expire_time and we get some errors because the token is expired
Asked
Active
Viewed 5,391 times
3 Answers
6
You can set a per-entry policy to evaluate the entry and determine the expiration time. As the token won't be modified within the cache, you can use expireAfterCreate
and have the other methods return the currentDuration
to not modify it. From the docs,
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));

Ben Manes
- 9,178
- 3
- 35
- 39
0
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

Hari Krishna
- 3,658
- 1
- 36
- 57
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);
}
}

Alex Kotikhov
- 1
- 1