我认为您正在寻找refreshAfterWrite
并覆盖CacheLoader.reload(K, V)
. 这是解释细节的帖子:https ://github.com/ben-manes/caffeine/wiki/Refresh
您的案例的实施将类似于:
@Log4j2
@Configuration
public class CacheConfig {
@Bean
public Cache<String,Item> caffeineConfig() {
return Caffeine.newBuilder()
.refreshAfterWrite(10, TimeUnit.SECONDS)
.build(new ConditionalCacheLoader<>(this::shouldReload, this::load));
}
private Item load(String key){
//load the item
return null;
}
private boolean shouldReload(Item oldValue){
//your condition logic here
return true;
}
private static class Item{
// the item value can contain any data
}
private static class ConditionalCacheLoader<K,V> implements CacheLoader<K,V>{
private final Predicate<V> shouldReload;
private final Function<K,V> load;
protected ConditionalCacheLoader(Predicate<V> shouldReload, Function<K, V> load) {
this.shouldReload = shouldReload;
this.load = load;
}
@Override
public V load(K key) throws Exception{
return load.apply(key);
}
@Override
public V reload(K key, V oldValue) throws Exception {
if (shouldReload.test(oldValue)){
return load(key);
}else {
return oldValue;
}
}
}
}