2016-03-18 71 views
0

我需要失敗的條目,而我試圖用以下語句來建立的緩存:HOWTO負載番石榴項

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:遞歸負載:...

問題如何僅向緩存添加失敗條目?

回答

0

CacheLoader.load(K)僅在沒有「給定鍵的已裝載值」(CacheBuilder.build(LoadingCache))時才被調用。

因此,呼籲從CacheLoader.load(K)LoadingCache.get(K)創建,如果允許執行,將遞歸太深導致StackOverflowError拋出一個遞歸負載。

從您示例中提供的信息看來,您不需要LoadingCache<K, V>,而只需要Cache<K, V>。撥打CacheBuilder.build(),不要撥打CacheLoader<K, V>

有關更多詳細信息,請參閱CachesExplained · google/guava Wiki