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

5

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

目前我正在进行以下操作:

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

        }

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


1
“Cache”有一个名为“invalidateAll()”的方法,可以清除所有条目。我没有看到你调用它。 - shmosel
既然你在使用Google库,我会把这个关于水平对齐的说明留下来,这是来自Google的Java风格指南。 - shmosel
1
使用Google库和采用Google编码风格是无关紧要的。(尽管我也觉得OP的水平对齐有点令人不安 :P) - Adrian Shum
最大的问题是,虽然与主题无关,但 OP 不恰当地使用了枚举。 - Adrian Shum
OP - 原始帖子 - Adrian Shum
1个回答

9

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

话虽如此,如果您打算每天重新加载条目,为什么只在四天后过期缓存内容(.expireAfterWrite(4, TimeUnit.DAYS))?只需将4更改为1即可每天重新加载内容。

此外,正如Adrian Shum所提到的,您正在误用枚举。 public enum PeriodicUpdater几乎肯定应该是public class PeriodicUpdater


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接