用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秒运行一次?

谢谢

qq2290279 回答:用Java缓存数据

在条目从其上次写入起经过该阈值之后,将在读取时触发刷新。

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

然后可以将其与到期结合使用,以便在不活动的条目到期时重新加载流行的条目。在这种情况下,刷新避免了呼叫者因周期性延迟而重新加载条目的惩罚,因为这种延迟是隐藏的,同时还可以确保它不会过时。

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

本文链接:https://www.f2er.com/2312148.html

大家都在问