javajcacheehcache-3

EhCache 3: How to unwrap statistics bean?


<?xml version="1.0" encoding="UTF-8"?>
<config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
        xmlns='http://www.ehcache.org/v3'
        xsi:schemaLocation="
        http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.1.xsd
        http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.1.xsd">

    <service>
        <jsr107:defaults enable-management="false" enable-statistics="true"/>
    </service>

    <cache alias="mySlidingExpiryJCache">
        <key-type>java.lang.Long</key-type>

        <expiry>
            <tti unit="seconds">2</tti>
        </expiry>
        <resources>
            <heap unit="entries">200</heap>
        </resources>
        <jsr107:mbeans enable-statistics="true"/>
    </cache>
</config>

I want to show statistics by extracting the MBean, however I don't know how, because on the net I can see only the bean injected programmatically (see also this SO question).

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

Any advice ?


Solution

  • You enabled JSR107/JCache statistics. Those are available via JMX. If you want to access those JMX beans programmatically, you can do something like this:

    Cache cache = // a JSR107 cache
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("javax.cache:type=CacheStatistics," +
      "CacheManager=" + cache.getCacheManager().getURI().toString() +
      ",Cache=" + mbeanSafe(cache.getName()));
    long hits = mBeanServer.getAttribute(name, "CacheHits");
    

    Be aware that the JCache Cache is created differently then you do it in your question. See the extensive documentation here: https://www.ehcache.org/documentation/3.0/107.html

    JSR107/JCache is a standard API that many Java caches support. It also includes the exposure of statistics via JMX. The available metrics are defined at: https://github.com/jsr107/jsr107spec/blob/master/src/main/java/javax/cache/management/CacheStatisticsMXBean.java