0
我有每天從db加載的所有客戶詳細信息的緩存。但是在加載每日客戶細節之前,我需要刪除緩存中的所有以前的條目。Java Guava Cache:如何清除所有緩存條目?
目前我做的:
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()'清除所有的條目,我沒有看到你調用它 – shmosel
由於您使用的是谷歌庫,我將在[水平對齊](https://google.github.io/ styleguide/javaguide.html#s4.6.3-horizontal-alignment)谷歌的Java風格指南 – shmosel
使用谷歌圖書館和採用谷歌編碼風格是不相干的(儘管我發現OP的水平對齊也有點令人不安):P) –