java - 在 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 秒运行一次?
谢谢
解决方案
自上次写入后条目老化超过该阈值后,读取时触发刷新。
当对条目的第一个陈旧请求发生时,将执行自动刷新。触发刷新的请求将对 CacheLoader.reload 进行异步调用并立即返回旧值。
然后可以将其与过期相结合,以便重新加载热门条目,而不活动的条目将过期。在这种情况下,刷新避免了调用者定期阻止重新加载条目的惩罚,因为这种延迟是隐藏的,同时也确保它不会变得太陈旧。
定期重新加载缓存最好由您自己的线程提供服务。例如使用ScheduledExecutorService
可以批量重新加载所有内容。
推荐阅读
- firebase - 我可以使用 gcloud 而不是 Firebase CLI 部署我的 Firebase 托管网页吗?
- java - 列出Java中特定类的所有子类
- html - 如何拆分按钮内的文本
- ruby-on-rails - Mongoid 动态 store_in
- scala - 无法使用 Spark SQL 正确读取 Impala 视图
- java - 如果在 try 块中初始化,则在 catch 块中处理 JFrame
- python - 如何使用 Python 从这个 javascript 页面中刮取职业道路的职位名称
- javascript - 如何在引导程序中将方形 div 居中在两列的中间?
- yii2 - 如何在 swagger yii2 中将数组添加到参数?
- r - 识别自变量之间的最高相关性值并排除与 r 中因变量的最低相关性