如何使用Google Guava LoadingCache实现具有时间驱逐和后备的缓存

时间:2016-12-06 02:32:45

标签: java caching google-guava-cache

Google Guava的缓存在阅读https://github.com/google/guava/wiki/CachesExplained

之后非常棒
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .removalListener(MY_LISTENER)
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });

我想要实现的内容需要满足以下要求:

  1. 特定密钥的缓存应在10分钟后过期,以便下一次调用get(密钥)将始终调用createExpensiveGraph(key)来更新并重置计时器(expireAfterWrite已经这样做我相信)。
  2. 如果由于某些意外错误而导致createExpensiveGraph(key)的下一次通话失败,即使下一次通话在10分钟后发生,我仍然希望使用旧值。
  3. 我认为1,它是番石榴LoadingCache的本质,但对于2,我们如何在保持1的同时实现它呢?

0 个答案:

没有答案