JAVA Guava缓存刷新现有元素

huangapple go评论62阅读模式
英文:

JAVA Guava cache refresh existing elements

问题

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

这是我的代码片段:

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

//我的主要方法
public Integer load(String key){
    Integer value = cache.getIfPresent(key);
    if(value == null){
        value = getKeyFromServer(key);
        //插入到缓存中
        cache.put(key, value);
    }
    return value;
}

我想增强上述代码,以便按如下所示刷新缓存映射中的元素:

//1. 遍历缓存映射
for(e in cache){
    //2. 从服务器获取新元素值
    value = getKeyFromServer(e.getKey());
    //3. 更新缓存
    cache.put(key, value);
}
英文:

I am using Guava to handle caching in my web application; I want to auto refresh the existing elements in my cache every 10 minutes.

this is my snippet code:

private Cache&lt;String, Integer&gt; 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;
}

I want to enhance the above code in order to refresh the elements gathered in my cache map as bellow:

 //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

得分: 0

你需要更多地使用Guava Cache。没有必要调用getIfPresent或者put,因为机制会被自动处理。

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

请注意,在Spring 5中,Guava Cache已被弃用:https://stackoverflow.com/a/44218055/8230378(你用spring-boot标记了该问题)。

英文:

You have to use Guava Cache a bit more. There is no need to call getIfPresent or put as the mechanism is handled automatically.

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

Source: https://github.com/google/guava/wiki/CachesExplained

Please note that Guava Cache is deprecated in Spring 5: https://stackoverflow.com/a/44218055/8230378 (you labeled the question with spring-boot).

huangapple
  • 本文由 发表于 2020年9月11日 02:30:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63835700.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定