Google Guava Cache – 在运行时更改驱逐超时值
我使用以下内容:
LoadingCache inQueueLoadingCache = CacheBuilder.newBuilder() .expireAfterWrite(120, TimeUnit.SECONDS) .removalListener(inQueueRemovalListener) .build(inQueueCacheLoader);
每120秒后,缓存条目被逐出,并按预期工作。
我的问题是:如何更改当前缓存的超时值,比如120到60秒? 在此更改期间缓存条目会发生什么?
简短回答:您无法更改逐出超时值或LoadingCache
创建的Cache
/ LoadingCache
任何属性。
无论如何,你为什么要改变超时? (还要记住Guava缓存非常简单。)如果你确实想要更改超时,你有两个选择:
-
使用目标语义创建新的
Cache
并复制旧的缓存内容,例如。LoadingCache
newCache = CacheBuilder.newBuilder() .expireAfterWrite(60, TimeUnit.SECONDS) .removalListener(inQueueRemovalListener) .build(inQueueCacheLoader); newCache.putAll(inQueueLoadingCache.asMap()); 但你会放宽原始访问时间等。
- 根本不使用
CacheBuilder
并自己实现LoadingCache
,例如使用AbstractLoadingCache
LoadingCache
实现和您自己的策略来更改超时。 但这并不容易,因为你有很好的LoadingCache
的API,但你必须自己实现整个事情(我尝试了一次,但结束使用比Guava更高级的缓存)。