實現 Expiry 接口
public class CaffeineExpiry implements Expiry<String, Object> {
@Override
public long expireAfterCreate(@NonNull String key, @NonNull Object value, long currentTime) {
return 0;
}
@Override
public long expireAfterUpdate(@NonNull String key, @NonNull Object value, long currentTime, @NonNegative long currentDuration) {
return currentDuration;
}
@Override
public long expireAfterRead(@NonNull String key, @NonNull Object value, long currentTime, @NonNegative long currentDuration) {
return currentDuration;
}
}
注意:如果使用常規的 put(key, value) 方法,則需要 expireAfterCreate 方法返回具體的值;下文使用 put(key, value, duration, timeUnit) 方法,expireAfterCreate 方法可以範圍任意值,不影響緩存過期時間。
配置
@Configuration
public class CaffeineConfig {
@Bean
public Cache<String, Object> caffeineCache() {
return Caffeine.newBuilder()
.expireAfter(new CaffeineExpiry())
.initialCapacity(100)
.maximumSize(1000)
.build();
}
}
使用
@Component
public class CaffeineCacheService {
@Autowired
Cache<String, Object> caffeineCache;
public void set(String key, Object value, long duration, TimeUnit unit) {
caffeineCache.policy().expireVariably().ifPresent(e->{
e.put(key, value, duration, unit);
});
}
public <T> T get(String key) {
return (T)caffeineCache.getIfPresent(key);
}
}
參考
Eviction#time-based
解讀JVM級別本地緩存Caffeine青出於藍的要訣3 —— 講透Caffeine的數據驅逐淘汰機制與用法
Spring 緩存動態設置過期時間 - Caffeine