我试图加深我对咖啡因缓存的理解。我想知道是否有一种方法可以为缓存中填充的条目指定超时,但其余记录没有基于时间的过期时间。
本质上我想有以下界面:
put(key, value,timeToEXEMY)
//输入指定时间的键和值
put(key, value)
//输入一个没有时间的键值
我可以编写接口和管道,但我想了解如何为上述两个需求配置caffeine。我也愿意拥有两个独立的caffeine缓存实例。
这可以通过使用自定义过期策略并利用不可达的持续时间来完成。最大持续时间是Long.MAX_VALUE
,以纳秒为单位为292年。假设您的记录在过期时保持不变,那么您可以将缓存配置为,
LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
.expireAfter(new Expiry<Key, Graph>() {
public long expireAfterCreate(Key key, Graph graph, long currentTime) {
if (graph.getExpiresOn() == null) {
return Long.MAX_VALUE;
}
long seconds = graph.getExpiresOn()
.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));
我目前正在研究这个主题,我受到这几篇文章的启发,我与你分享对我来说很有效的解决方案。
@EnableCaching
@Configuration
public class CaffeineConfiguration {
@Autowired
private ApplicationProperties applicationProperties;
@Bean
public Caffeine caffeineConfig() {
return Caffeine.newBuilder().expireAfter(new Expiry<String, Object>() {
@Override
public long expireAfterCreate(String key, Object value, long currentTime) {
long customExpiry = applicationProperties.getCache().getEhcache().getTimeToLiveSeconds();
if (key.startsWith("PREFIX")) {
customExpiry = 60;
}
return TimeUnit.SECONDS.toNanos(customExpiry);
}
@Override
public long expireAfterUpdate(String key, Object value, long currentTime,
long currentDuration) {
return currentDuration;
}
@Override
public long expireAfterRead(String key, Object value, long currentTime,
long currentDuration) {
return currentDuration;
}
});
}
@Bean
public CacheManager cacheManager(Caffeine caffeine) {
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
caffeineCacheManager.getCache(PROVIDER_RESPONSE);
caffeineCacheManager.getCache(BCU_RESPONSE);
caffeineCacheManager.setCaffeine(caffeine);
return caffeineCacheManager;
}
}