咖啡因支持可变过期,其中条目的持续时间必须独立计算。如果你想让所有条目同时过期,你可以写,
Caffeine.newBuilder()
.expireAfter(new Expiry<K, V>() {
public long expireAfterCreate(K key, V value, long currentTime) {
var toMidnight = Duration.between(LocalDate.now(),
LocalDate.now().plusDays(1).atStartOfDay());
var toNoon = Duration.between(LocalTime.now(), LocalTime.NOON);
return toNoon.isNegative() ? toMidnight.toNanos() : toNoon.toNanos();
}
public long expireAfterUpdate(K key, V value,
long currentTime, long currentDuration) {
return currentDuration;
}
public long expireAfterRead(K key, V value,
long currentTime, long currentDuration) {
return currentDuration;
}
}).build();
对于这样一个简单的任务,使用过期可能是矫枉过正。相反,如果您想清除缓存,那么计划任务可以代替,正如@alexzander-zharkov 建议的那样。
@Scheduled(cron = "0 0,12 * * *")
public void clear() {
cache.invalidateAll();
}
由于这会清空缓存,因此会在重新加载条目时降低性能。相反,您可能会异步刷新缓存,以便重新加载条目而不会惩罚任何调用者。
@Scheduled(cron = "0 0,12 * * *")
public void refresh() {
cache.refreshAll(cache.asMap().keySet());
}