如何使用条目加载番石榴

Howto load guava with entries

我需要失败条目的缓存,我正在尝试使用以下语句构建它:

    failedJobCache =
            CacheBuilder.newBuilder()
                    .maximumSize(100) // maximum 100 records can be cached
                    .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access
                    .build(new CacheLoader<String, JobDto>() {
                        @Override
                        public JobDto load(String s) throws Exception {
                            JobDto found = failedJobCache.get(s);
                            if (found != null)
                                return found;
                            else
                                return null;
                        }
                    });

并且:

// add failed entries
failedJobCache.put(jobDto.getUniqueId(), jobDto);

// respective check before running the job if its
// already in the cache and should be skipped:
JobDto existing = failedJobCache.get(jobDto.getUniqueId());
if (existing != null) {
    logger.debug("Nothing to do, job already processed!" + jobDto.getUniqueId());
    return;
}

不幸遇到:

线程中出现异常 "main" com.google.common.util.concurrent.UncheckedExecutionException:java.lang.IllegalStateException:递归加载:...

问题如何只将失败的条目添加到缓存?

CacheLoader.load(K) is only called if there isn't "an already-loaded value for a given key" (CacheBuilder.build(LoadingCache)).

因此,调用 LoadingCache.get(K) from CacheLoader.load(K) creates a recursive load that, if allowed to execute, would recurse too deeply causing a WhosebugError 被抛出。

根据您示例中提供的信息,您似乎不需要 LoadingCache<K, V> but just a Cache<K, V>. Call CacheBuilder.build() without a CacheLoader<K, V>

有关详细信息,请参阅 CachesExplained · google/guava Wiki

加载函数似乎有一个递归。当您尝试在缓存中加载条目并且加载程序函数中的某处尝试再次调用它时,就会发生这种情况。

您可以调试并识别进行此类调用的方法。