Tuesday, June 9, 2015

Use JMX to monitor Hibernate 4.3 statistics (with Spring)

To find out hibernate cache’s performance, like cache hit/miss ratio, JMX can be convenient. Before Hibernate 4.3, there is a StatisticsService class can be used. But Hibernate 4.3 removed this class.  If the project also uses Spring framework, it can still be done. 

The original solution came from Marcel Stor from here. This article try to compliment it with details.

0. What you need

  • JDK1.7 +
  • Maven 3.2.1+
  • Spring 4.1.0.RELEASE
  • Hibernate 4.3.4.Final

1. Define Java class

One Jave class is needed. Add the following class to the project.  The class is defined as a normal Spring bean with @Component annotation.

package com.shengwang.demo.statistics;

import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HibernateStatisticsFactoryBean implements FactoryBean<Statistics> {

@Autowired
private SessionFactory sessionFactory;

@Override
public Statistics getObject() throws Exception {
return sessionFactory.getStatistics();
}

@Override
public Class<?> getObjectType() {
return Statistics.class;
}

@Override
public boolean isSingleton() {
return true;
}
}

2. Configure Spring


Configure Spring, add following to the spring configuration xml file.

<!-- ==================================== -->
<!-- Hibernate 4.3 Statistics for JMX -->
<!-- ==================================== -->
<bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="Hibernate:type=statistics">
<ref bean="hibernateStatisticsFactoryBean"/>
</entry>
</map>
</property>
</bean>

The bean hibernateStatisticsFactoryBean used is the Class defined above. 


All done!


3. Check from JConsole


Run JConsole, the JMX tool shipped with JDK, connect to the running project. Now hibernate statistics can be monitored!


Connect to the Java application process.

image

Now the Hibernate performance can be monitored by JMX, for example the 2nd level cache hit ratio in the following snapshot.


image

1 comment:

Powered by Blogger.

About The Author

My Photo
Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List