首页 > 解决方案 > 带有统计信息的异步​​咖啡因缓存

问题描述

这篇关于实现 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()方法。

这有什么原因吗?

标签: javaguavacaffeine

解决方案


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}

推荐阅读