我正在使用以下内容:
LoadingCache<String, Long> inQueueLoadingCache = CacheBuilder.newBuilder()
.expireAfterWrite(120, TimeUnit.SECONDS)
.removalListener(inQueueRemovalListener)
.build(inQueueCacheLoader);
每 120 秒后,缓存条目就会被逐出,并且按预期工作。
我的问题是:如何更改当前缓存的超时值,例如从 120 秒更改为 60 秒?在此更改期间缓存条目会发生什么?
最佳答案
简短回答:您无法更改逐出超时值或由 CacheBuilder
创建的 Cache
/LoadingCache
的任何属性。
无论如何,您为什么要更改超时? (还要记住,Guava 缓存非常简单。)如果您确实想更改超时,您有两种选择:
使用目标语义创建新的
Cache
并复制旧的缓存内容,例如。LoadingCache<String, Long> newCache = CacheBuilder.newBuilder() .expireAfterWrite(60, TimeUnit.SECONDS) .removalListener(inQueueRemovalListener) .build(inQueueCacheLoader); newCache.putAll(inQueueLoadingCache.asMap());
但你会失去原来的访问时间等。
- 根本不要使用
CacheBuilder
并自行实现LoadingCache
,例如使用AbstractLoadingCache
使用您自己的更改超时策略的骨架实现。但这并不容易,因为你有很好的LoadingCache
的 API,但你必须自己实现整个事情(我尝试过一次,但最终使用了比 Guava 更高级的缓存)。
关于java - Google Guava Cache - 在运行时更改驱逐超时值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26843814/