首页 > 解决方案 > 在 Java 中缓存数据

问题描述

我的实现非常简单,但它没有做应该做的事情。我正在使用这个缓存库:https ://github.com/ben-manes/caffeine

当我部署应用程序时:

Calls Controller Endpoint -> First time loads data to cache (works fine) -> Wait 10 seconds -> refresh data to cache -> wait 10 seconds -> ... over and over

第一次加载完美。问题是 10 秒后,数据的重新加载没有运行。

控制器

   MyData myData = MyData.getInstance();
   Map<String, List<String>> tableOne = myData.cache.get("tableOne");

MyData 类

public LoadingCache<String, Map<String, List<String>>> cache;

public static MyData getInstance() {
    if (instance == null) {
        synchronized (MyData.class) {
            if (instance == null) {
                instance = new MyData();
            }
        }
    }
    return instance;
}

 private MyData() {
    this.cache = Caffeine.newBuilder()
            .refreshAfterWrite(10, TimeUnit.SECONDS)
            .build(key -> MyData.getInstance().loadData(key));
}

private Map<String, List<String>> loadData(String key) {
       // Loads Data. This is only called once and never again!
}

任何线索为什么refreshAfterWrite不每 10 秒运行一次?

谢谢

标签: javacaffeine

解决方案


自上次写入后条目老化超过该阈值后,读取时触发刷新。

当对条目的第一个陈旧请求发生时,将执行自动刷新。触发刷新的请求将对 CacheLoader.reload 进行异步调用并立即返回旧值。

然后可以将其与过期相结合,以便重新加载热门条目,而不活动的条目将过期。在这种情况下,刷新避免了调用者定期阻止重新加载条目的惩罚,因为这种延迟是隐藏的,同时也确保它不会变得太陈旧。

定期重新加载缓存最好由您自己的线程提供服务。例如使用ScheduledExecutorService可以批量重新加载所有内容。


推荐阅读