运行时的Ehcache缓存大小

时间:2012-11-05 10:17:07

标签: java ehcache

我正在生产中运行一个大型VM,并希望在运行时了解有关我的缓存大小的更多信息。我的缓存都基于ehache

在运行时查看单个缓存大小的最佳方法是什么。使用JMX或API

是否有任何选项可以通过对CacheManager的普通旧java调用进行配置,或者(暂时忽略JMX)是否必须在一个大字符串中构建XML配置slug?

3 个答案:

答案 0 :(得分:14)

是的,使用Ehcache,您可以配置缓存并仅通过Java代码检索其大小(无XML配置)。集成一切的确切方法取决于您的特定架构;我将假设泽西做API和Guice用于依赖注入。

定义缓存

通过依赖注入使缓存管理器可用。这可以通过Guice模块完成:

@Provides
@Singleton
CacheManager provideCacheManager() {
  CacheManager cacheManager = CacheManager.create();

  /* very basic cache configuration */
  CacheConfiguration config = new CacheConfiguration("mycache", 100)
    .timeToLiveSeconds(60)
    .timeToIdleSeconds(30)
    .statistics(true);

  Cache myCache = new Cache(config);
  cacheManager.addCacheIfAbsent(myCache);

  return cacheManager;
}

请注意,mycache已启用统计信息。

同样,使用缓存可以完全用Java代码完成,但取决于您的架构和设计。通常我使用方法拦截(通过AOP)来做这个,但这是另一个主题。

通过REST API获取缓存统计信息

鉴于您的CacheManager可通过依赖注入获得,您可以将其连接到REST端点并允许访问缓存统计信息:

@Path("stats")
@Produces("text/plain")
public class StatsResource {
  @Inject private CacheManager cacheManager;

  @GET
  public String stats() {
    StringBuffer sb = StringBuffer();

    /* get stats for all known caches */
    for (String name : cacheManager.getCacheNames()) {
      Cache cache = cacheManager.getCache(name);
      Statistics stats = cache.getStatistics();

      sb.append(String.format("%s: %s objects, %s hits, %s misses\n",
        name,
        stats.getObjectCount(),
        stats.getCacheHits(),
        stats.getCacheMisses()
      ));
    }
    return sb.toString();
  }
}

现在,您可以通过REST调用获取有关缓存的信息:

GET /stats

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8

mycache: 8 objects, 59 hits, 12 misses

JMX怎么样?

Ehcache可以轻松地将缓存管理器注册到MBean服务器。它可以用Java代码完成。更新您的Guice模块,将cacheManager注册到系统MBeanServer

MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(cacheManager, mBeanServer, false, false, false, true);

现在,您可以将JConsole附加到Java进程,并在MBean net.sf.ehcache.CacheStatistics中查找缓存统计信息。

答案 1 :(得分:1)

在EhCache 3中(至少在我使用的3.5版本中),您可以通过缓存统计信息访问缓存大小。

首先,您需要在缓存管理器上注册统计服务:

StatisticsService statisticsService = new DefaultStatisticsService();
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .using(statisticsService)
        .build();
cacheManager.init();

然后,您可以检索缓存中的统计信息,它包含各层的大小(在EhCache 3中,您有三个不同的层:堆,磁盘和离线)

CacheStatistics ehCacheStat = statisticsService.getCacheStatistics("myCache");
ehCacheStat.getTierStatistics().get("OnHeap").getMappings();//nb element in heap tier
ehCacheStat.getTierStatistics().get("OnHeap").getOccupiedByteSize()//size of the tier

答案 2 :(得分:0)

JMX绝对是一个可行的解决方案。 EhCache文档专门针对此page

通过JMX配置EhCache的

Here's an example。链接的文章包含一个Spring配置,但如果你不使用Spring,它很容易翻译成原生Java。