java - 带有统计信息的异步咖啡因缓存
问题描述
在这篇关于实现 Caffeine 异步缓存的博客文章之后,我们想从缓存中获取统计数据。
我们使用2.7.0
的是咖啡因版本
但是,似乎AsyncCache
无法访问其统计信息:
private AsyncCache<String, Cat> asyncCache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.recordStats()
.maximumSize(100)
.buildAsync();
private Cache<String, Cat> cache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.maximumSize(100)
.recordStats()
.build();
....
cache.stats(); // this is possible
asyncCache.stats(); // no such method in asyncCache
另外,在查看AsyncCache的源代码并将其与Cache类进行比较时,async 类中没有任何stats()
方法。
这有什么原因吗?
解决方案
AsyncCache 提供了一个synchronous()
视图来提供一个阻塞直到异步计算完成的缓存。
/**
* Returns a view of the entries stored in this cache as a synchronous {@link Cache}. A mapping is
* not present if the value is currently being loaded. Modifications made to the synchronous cache
* directly affect the asynchronous cache. If a modification is made to a mapping that is
* currently loading, the operation blocks until the computation completes.
*
* @return a thread-safe synchronous view of this cache
*/
Cache<K, V> synchronous();
invalidate(key)
这可以很方便地执行没有异步对应的操作,例如。它还提供对统计数据和策略元数据的访问。
AsyncCache<Integer, Integer> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.recordStats()
.buildAsync();
// Perform application work
for (int i = 0; i < 4; i++) {
cache.get(1, key -> key);
}
// Statistics can be queried and reported on
System.out.println(cache.synchronous().stats());
在这种情况下,我们希望第一次未命中加载条目,以便后续查找成功。
CacheStats{hitCount=3, missCount=1, loadSuccessCount=1, loadFailureCount=0, totalLoadTime=8791091, evictionCount=0, evictionWeight=0}
推荐阅读
- tensorflow.js - How to get indices of a specific value in a tensor in tensorflow-js?
- java - IntelliJ 中 Flink WordCount 输出中的数字
- javascript - 如何从我要删除的待办事项应用程序中删除列表?
- linux - 无法在 Linux 上删除文件
- javascript - 我如何在 Vue.js 中获得 axios 响应( v-on:click )(async / try,catch)?
- apache-spark - 如果到目前为止在 Pyspark 中还有其他所有事件,如何捕获第一个事件?
- c# - EntityFramework 包含但不保证存在
- reactjs - getByText 找不到元素
- calendar - 如何通过 URL 在 Google 日历中包含来宾和创建新活动的通知
- css - 如何停止`-webkit-background-clip:text`使文本变薄?