有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring boot JAVA Guava缓存刷新现有元素

我使用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);
 }

共 (1) 个答案

  1. # 1 楼答案

    你必须多用番石榴酱。由于机制是自动处理的,因此无需调用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标记了这个问题)