JAVA 番石榴缓存刷新现有元素

JAVA Guava cache refresh existing elements

我正在使用 Guava 来处理我的 Web 应用程序中的缓存;我想每 10 分钟自动刷新缓存中的现有元素。

这是我的代码片段:

private Cache<String, Integer> cache = CacheBuilder.newBuilder.build();

//my main method
public Integer load(String key){
    Integer value = cache.getIfPresent(key)
    if(value == null){
        value = getKeyFromServer(key);
        //insert in my cache
        cache.put(key, value);
    }
    return value;
}

我想改进上面的代码,以便如下刷新缓存映射中收集的元素:

 //1. iterate over cache map
 for(e in cache){
    //2. get new element value from the server
    value = getKeyFromServer(e.getKey());
    //3. update the cache
    cache.put(key, value);
 }

你要多用一点Guava Cache。无需调用 getIfPresentput,因为该机制会自动处理。

LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .build(
           new CacheLoader<String, Integer>() {
             @Override
             public Integer load(Key key) throws Exception {
               return getKeyFromServer(key);
             }
           });

来源:https://github.com/google/guava/wiki/CachesExplained

请注意,Guava Cache 在 Spring 5 中已弃用:(您用 spring-boot 标记了问题)。