【问题标题】:JAVA Guava cache refresh existing elementsJAVA Guava缓存刷新现有元素
【发布时间】:2020-09-10 18:30:02
【问题描述】:

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

这是我的 sn-p 代码:

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);
 }

【问题讨论】:

    标签: java spring-boot guava


    【解决方案1】:

    你必须更多地使用 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 中已弃用:https://stackoverflow.com/a/44218055/8230378(您将问题标记为spring-boot)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多