Java Guava Cache:如何清除所有缓存条目?

use*_*267 3 java caching timer guava

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

目前我正在做:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里使用缓存:

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

        }
Run Code Online (Sandbox Code Playgroud)

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

dim*_*414 6

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

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

此外,正如 Adrian Shum 提到的,您正在滥用枚举。public enum PeriodicUpdater几乎可以肯定public class PeriodicUpdater