英文:
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<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;
}
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<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);
}
});
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
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论