本文介绍了Google Guava缓存-在运行时更改逐出超时值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下内容:

LoadingCache<String, Long> inQueueLoadingCache = CacheBuilder.newBuilder()
    .expireAfterWrite(120, TimeUnit.SECONDS)
    .removalListener(inQueueRemovalListener)
    .build(inQueueCacheLoader);

每隔120秒,将逐出缓存项并按预期工作。

After every 120 seconds, the cache entries are evicted and it works as expected.

我的问题是:如何更改当前缓存的超时值,例如从120秒更改为60秒?

My question is: How do I change the timeout value, say from 120 to 60 seconds, for the current cache? What will happen to the cache entries during this change?

推荐答案

简短答案:您不能更改逐出超时值,或者任何其他更改 Cache / LoadingCache 的属性,由 CacheBuilder 创建。

Short answer: you can't change eviction timeout value, or any property of Cache / LoadingCache created by CacheBuilder.

无论如何,为什么要更改超时时间? (也请记住,Guava缓存非常简单。)如果您确实要更改超时,则有两种选择:

Anyway, why would you want to change the timeout? (Also bare in mind that Guava Caches are quite simple.) If you really do want to change the timeout, you have two choices:


  • 使用目标语义创建新的 Cache 并复制旧的缓存内容,例如。

  • create new Cache with target semantics and copy old cache contents, ex.

LoadingCache<String, Long> newCache = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.SECONDS)
    .removalListener(inQueueRemovalListener)
    .build(inQueueCacheLoader);
newCache.putAll(inQueueLoadingCache.asMap());

但是您会丢失原始访问时间等。

but you'll loose original access times etc.

这篇关于Google Guava缓存-在运行时更改逐出超时值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:47