gpt4 book ai didi

Java Guava 缓存: How to clear all cache entries?

转载 作者:行者123 更新时间:2023-12-01 20:57:14 25 4
gpt4 key购买 nike

我有缓存,每天从数据库加载所有客户详细信息。但在加载每日客户详细信息之前,我需要删除缓存中以前的所有条目。

目前我正在做:

public enum PeriodicUpdater {

TIMER;
private final AtomicBoolean isPublishing = new AtomicBoolean(false);
private final long period = TimeUnit.DAYS.toMillis(1);

@Autowired
@Qualifier("TestUtils") @Setter
private TestUtils testUtils;

public synchronized boolean initialize() {
return initialize(period, period);
}


boolean initialize(long delay, long period) {
if (isPublishing.get()) {
return false;
}
TimerTask task = new TimerTask() {

@Override public void run() {
try {

String path = getFile();
if(TestUtils.getFileNameCache().getIfPresent(path) == null) {
TestUtils.setFileNameCache(testUtils.buildFileCache(path));
}
} catch (Exception e) {
log.warn("Failed!", e);
}
}
};
Timer timer = new Timer("PeriodicUpdater", true); // daemon=true
timer.schedule(task, delay, period);
isPublishing.set(true);
return true;
}
}

我在这里使用缓存:

    public class TestUtils {

private static Cache<String, Map<String, List<String>>> fileCache = CacheBuilder
.newBuilder()
.expireAfterWrite(4, TimeUnit.DAYS)
.build();


public TestUtils() {

String path = getFile();
fileNameCache = buildFileCache(path);
}

public Cache<String, String> buildFileCache(String path) {

Cache<String, String> fileList = CacheBuilder
.newBuilder()
.expireAfterWrite(4, TimeUnit.DAYS)
.build();

fileList.put(path, new Date().toString());

return fileList;
}
/* doing some stuff with the cache */

}

这样做正确吗?我没有看到缓存被清除。如果我错了,有人可以纠正我吗?

最佳答案

Cache.invalidateAll()将清除当前缓存中的所有条目。

也就是说,如果您打算每天重新加载条目,为什么只每四天使缓存内容过期(.expireAfterWrite(4, TimeUnit.DAYS))?只需将 4 更改为 1 即可每天重新加载内容一次。

此外,正如 Adrian Shum 提到的,您滥用了枚举。 public enum periodicupdater 几乎肯定应该是public class periodicupdater

关于Java Guava 缓存: How to clear all cache entries?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42150174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com