Terracotta Ehcache 10.7 | Ehcache API Developer Guide | Management and Monitoring with Ehcache | Making use of the ManagementRegistry
 
Making use of the ManagementRegistry
By default, a ManagementRegistry is automatically discovered and enabled, but can only be accessed by Ehcache internal services. If you wish to make use of it, you should create your own instance and pass it to the cache manager builder as a service:
CacheManager cacheManager = null;
try {
DefaultManagementRegistryConfiguration registryConfiguration =
new DefaultManagementRegistryConfiguration()
.setCacheManagerAlias("myCacheManager1"); // 1
ManagementRegistryService managementRegistry =
new DefaultManagementRegistryService(registryConfiguration); // 2

CacheConfiguration<Long, String> cacheConfiguration =
CacheConfigurationBuilder.newCacheConfigurationBuilder(
Long.class, String.class,
ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(1, MemoryUnit.MB).offheap(2, MemoryUnit.MB))
.build();

cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("myCache", cacheConfiguration)
.using(managementRegistry) // 3
.build(true);

Object o =
managementRegistry.withCapability("StatisticCollectorCapability")
.call("updateCollectedStatistics",
new Parameter("StatisticsCapability"),
new Parameter(Arrays.asList("Cache:HitCount", "Cache:MissCount"),
Collection.class.getName()))
.on(Context.create("cacheManagerName", "myCacheManager1"))
.build()
.execute()
.getSingleResult();
System.out.println(o);

Cache<Long, String> aCache = cacheManager.getCache(
"myCache", Long.class, String.class);
aCache.put(1L, "one");
aCache.put(0L, "zero");
aCache.get(1L); // 4
aCache.get(0L); // 4
aCache.get(0L);
aCache.get(0L);

Context context = StatsUtil.createContext(managementRegistry); // 5

StatisticQuery query =
managementRegistry.withCapability("StatisticsCapability") // 6
.queryStatistic("Cache:HitCount")
.on(context)
.build();

ResultSet<ContextualStatistics> counters = query.execute();

ContextualStatistics statisticsContext = counters.getResult(context);

Assert.assertThat(counters.size(), Matchers.is(1));
}
finally {
if(cacheManager != null) cacheManager.close();
}
1
Optional: give a name to your cache manager by using a custom configuration
2
Create an instance of org.ehcache.management.registry.DefaultManagementRegistryService. This is only required because the service is used below.
3
Pass it as a service to the cache manager (if you only want to configure the ManagementRegistry, you can just pass the configuration instead)
4
Perform a few gets to increment the statistic's counter
5
Create the target statistic's context
6
Collect the get count statistic
Obviously, you may use the above technique to pass your own implementation of ManagementRegistry.