How To Monitor Ehcache In JMX With Spring Configuration

10-02-2015

As an alternative to the Ehcache Monitor, JMX creates a standard way of instrumenting classes and making them available to a management and monitoring infrastructure.

Overview

JMX creates a standard way of instrumenting classes and making them available to a management and monitoring infrastructure. The net.sf.ehcache.management package contains MBeans and a ManagementService for JMX management of ehcache. It is in a separate package so that JMX libraries are only required if you wish to use it - there is no leakage of JMX dependencies into the core Ehcache package.

Use net.sf.ehcache.management.ManagementService.registerMBeans(...) static method to register a selection of MBeans to the MBeanServer provided to the method. If you wish to monitor Ehcache but not use JMX, just use the existing public methods on Cache and CacheStatistics.

The Management package is illustrated in the follwing image.

Enable via Spring

To monitor Ehcache in JMX, we can easily configure necessary settings in Spring as follows:

<bean id="managementService" class="net.sf.ehcache.management.ManagementService"
      init-method="init"
      destroy-method="dispose">
    <constructor-arg ref="cacheManager"/>
    <constructor-arg ref="mbeanServer"/>
    <constructor-arg index="2" value="true"/>
    <constructor-arg index="3" value="true"/>
    <constructor-arg index="4" value="true"/>
    <constructor-arg index="5" value="true"/>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
    <property name="shared" value="true"/>
</bean>

As ehcache.xml file is located in the resources folder of maven project, configLocation value is classpath:ehcache.xml.

org.springframework.cache.ehcache package located in spring-context-support dependency:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>

If your project doesn't use Spring, then you can use following codes to monitor Ehcache:

CacheManager manager = new CacheManager();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);

Result

When using Ehcache as second-level cache provider, it is sometimes needed to remove entities from cache. For example, we can remove entities from second level cache when an outside process such as a MySQL administrator directly connected to modify the database (update/insert/delete). Therefore, by using Ehcache cache manager in JMX, we can remove entities as follow:

© 2019 All rights reserved. Codesenior.COM