How to get ehcache 3.1 statistics

前端 未结 4 1348
忘掉有多难
忘掉有多难 2020-12-19 07:32

With Ehcache 3.1, I have a case to know the size of elements that are currently stored in the ehcache and also the number of hits and misses that the cache has so far. I thi

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 08:05

    For Ehcache 3.5.2 as well as for any other JCache Provider you can use standard methods to enable statistics during cache configuration For instanse:

    ...
    MutableConfiguration config = new MutableConfiguration<>();
    config.setStatisticsEnabled(true);
    ...
    
    Cache myCache = cacheManager.createCache(CACHE_NAME, config);
    

    Then you could find register statics MXBean using the following method:

    public static CacheStatisticsMXBean getCacheStatisticsMXBean(final String cacheName) {
            final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = null;
            try {
                name = new ObjectName("*:type=CacheStatistics,*,Cache=" + cacheName);
            } catch (MalformedObjectNameException ex) {
                LOG.error("Someting wrong with ObjectName {}", ex);
            }
            Set beans = mbeanServer.queryNames(name, null);
            if (beans.isEmpty()) {
                LOG.debug("Cache Statistics Bean not found");
                return null;
            }
            ObjectName[] objArray = beans.toArray(new ObjectName[beans.size()]);
            return JMX.newMBeanProxy(mbeanServer, objArray[0], CacheStatisticsMXBean.class);
        }
    

    And if it is found enjoy your statistics:

    CacheStatisticsMXBean CacheStatBean = getCacheStatisticsMXBean(cacheName);
                if (CacheStatBean != null) {
                    LOG.debug("Cache hits #{} misses #{}", CacheStatBean.getCacheHits(), CacheStatBean.getCacheMisses());
                    LOG.debug("Cache hits %{} misses %{}", CacheStatBean.getCacheHitPercentage(),
                            CacheStatBean.getCacheMissPercentage());
                    LOG.debug("Cache gets #{}", CacheStatBean.getCacheGets());
                    LOG.debug("Cache evictions #{}", CacheStatBean.getCacheEvictions());
                    LOG.debug("Cache average get time {} milliseconds", CacheStatBean.getAverageGetTime());
                }
    

提交回复
热议问题