Java 如何获取Ehcache中的对象数?

Java 如何获取Ehcache中的对象数?,java,ehcache,Java,Ehcache,我正在使用Ehcache 2.10.4。我使用枚举配置缓存,如下所示: 失败的消息重播计数(“msgreplaycount”,50000,false,03600) 但是,当我检查尺寸时,它似乎从未驱逐/过期任何东西 public static String cacheStats() { StringBuilder sb = new StringBuilder("Storm in memory caches:"); for (int i = 0; i < TmaticInMe

我正在使用Ehcache 2.10.4。我使用枚举配置缓存,如下所示:

失败的消息重播计数(“msgreplaycount”,50000,false,03600)

但是,当我检查尺寸时,它似乎从未驱逐/过期任何东西

public static String cacheStats() {
    StringBuilder sb = new StringBuilder("Storm in memory caches:");
    for (int i = 0; i < TmaticInMemoryCache.values().length; i++) {
        TmaticInMemoryCache tmaticCache = TmaticInMemoryCache.values()[i];
        sb.append("\n  *  ").append(tmaticCache.name()).append(":");
        Cache c = tmaticCache.getCache();
        StatisticsGateway statistics = c.getStatistics();
        long hits = statistics.cacheHitCount();
        long misses = statistics.cacheMissCount();
        long size = statistics.getSize();
        long expired = statistics.cacheExpiredCount();
        long evicted = statistics.cacheEvictedCount();
        sb.append(String.format("(hits/misses: %d/%d, expired/evicted: %d/%d, current size: %d)", hits, misses, expired, evicted, size));
    }
    return sb.toString();
}
这些项目应该只在缓存中停留300秒,但它们似乎会永远停留。

  • 您的设置使用TTI而不是TTL,这意味着每次您点击一个条目时,它的到期时间都会按配置的数量延迟
  • 从底部打印的统计数据来看,与未命中相比,您的命中率非常低。这意味着您几乎从未从缓存中读取值
  • Ehcache没有即时到期机制。缓存中过期的条目将保留在那里,直到它们被请求(并因此被清除),或者直到缓存已满且逐出开始
从这些角度来看,你看到的数字是有意义的:你点击的少数条目看到它们的寿命延长了,其他条目只是停留在那里,很可能到目前为止无效,但从未清理过,驱逐不是一个问题,因为你远远低于容量


最后,您可以回答自己的问题,因为您可以显示缓存中的元素数。

因此,失败消息的大小\u REPLAY\u计数为317,但2天内未被命中或访问。大小应该是零,对吗?或者我遗漏了什么?在Ehcache中,只有与条目(如
get
)的交互才会导致删除过期条目。如果与缓存没有交互,则不会清理条目。关于:this.theCache.executeExpireElements();这样做可以吗?是的,这样做可以奏效,但在大型缓存上可能需要很长时间。
public int noOfCacheObject(String cacheName) {
    Ehcache cache = cacheManager.getEhcache(cacheName);

    if (cache == null) {
        return 0;
    }

    return cache.getKeys().size();
}
FAILED_MESSAGES_REPLAY_COUNTS:(hits/misses: 4/13665103, expired/evicted: 0/0, current size: 317)
public int noOfCacheObject(String cacheName) {
    Ehcache cache = cacheManager.getEhcache(cacheName);

    if (cache == null) {
        return 0;
    }

    return cache.getKeys().size();
}