带有统计信息的异步​​Caffeine缓存

时间:2019-06-19 05:43:44

标签: java guava caffeine

this关于实现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类进行比较时,异步类中没有stats()方法。

有什么理由吗?

1 个答案:

答案 0 :(得分:1)

AsyncCache提供一个synchronous()视图,以提供一个在异步计算完成之前会阻塞的Cache。

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