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 楼答案
你必须多用番石榴酱。由于机制是自动处理的,因此无需调用
getIfPresent
或put
资料来源:https://github.com/google/guava/wiki/CachesExplained
请注意,Guava Cache在Spring 5中被弃用:https://stackoverflow.com/a/44218055/8230378(您用
spring-boot
标记了这个问题)