基于Spring支持JMX

前言:

      基于Vert写的组件,其中在使用过程中碰到若干瓶颈问题,如果每个组件都采用日志方式,查看资源使用情况略微低廉点,所以采用了JMX来进行管理工作。

      提到JMX,就必须按照JMX的规范,写一大堆的MBean、MXBean、Agent等,想起来就挺麻烦的,这个时候想起来Spring支持JMX,发现虽然原理差不多使用MXBeanServer.register,但是就是Spring写得东西就是让你配置特别简单。

import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Aspect
@Component
@ManagedResource(objectName = "aop-vertx:name=VertxRedisAspect")
public class VertxRedisAspect  {

	private static Logger LOG = Logger.getLogger(VertxRedisAspect.class);

	private AtomicInteger redisPartitions = new AtomicInteger(0);


	public void sharePartitions(int count) {
		redisPartitions.set(count);
	}
}

 springXML的配置结构:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:ctx="http://www.springframework.org/schema/context"
	   xmlns:int="http://www.springframework.org/schema/integration/jmx"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	   		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
	   		http://www.springframework.org/schema/integration/jmx http://www.springframework.org/schema/integration/jmx/spring-integration-jmx.xsd">

	<ctx:mbean-server/>

	<ctx:mbean-export default-domain="aop-vertx"/>
	<int:mbean-export default-domain="aop-vertx"/>

	<bean id="rmiRegistry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean"
		  p:port="1099"/>

	<bean id="jmxServerConnector" class="org.springframework.jmx.support.ConnectorServerFactoryBean"
		  depends-on="rmiRegistry"
		  p:objectName="connector:name=rmi"
		  p:serviceUrl="service:jmx:rmi://localhost/jndi/rmi://localhost:1099/aop-vertx"/>

</beans>

 查看JConsole:

MBean下就有具体的操作和通知

个人结论:

      不管你做中间件还是其它服务化的,最好都支持JMX support,不仅仅为了自己,也为了本身系统的健壮性。

相关推荐