`
yznxing
  • 浏览: 367194 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

用spring连接jmx

    博客分类:
  • java
阅读更多

接着上一篇 “原生态连接jmx”的例子。

 

上一篇中,发布一个MBean还要实现接口,还要写一堆东西比较麻烦。如果使用spring的话,

spring会帮我们吧这些都做掉,之后的代码就变得异常简洁。

 

在使用了spring之后唯一需要的就是

 

一个main函数,

一个配置文件,

一个发布的MBean的POJO。

 

代码分别如下:

 

MBean的POJO:

 

 

/**
 * @author guoliang
 * @version 创建时间:2010-11-14 下午03:50:24 类说明
 */

public class MyHelloMBean {

    private static int count;

    public static synchronized void inc() {
        count++;
    }

    public static synchronized int cnt() {
        return count;
    }

    public String testMethod(String from) {
        return "hello world" + from;
    }

    private String testPrivateMethod() {
        System.out.println("testPrivateMethod");
        return "private";
    }
}
 

 

 

对应的jmx的配置文件

 

spring-jmx.xml。有兴趣的话可以看看源码,其实就是spring帮忙生成了MBeanInfo的信息。

具体可以参见:AbstractMBeanInfoAssembler的getMBeanInfo方法。

 

 

<?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd"
	default-autowire="byName">

	<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter"
		lazy-init="false">
		<property name="beans">
			<map>
				<entry key="bean:name=guoliangtest" value-ref="helloMBean" />
			</map>
		</property>
	</bean>
	
	<bean id="helloMBean" class="com.taobao.yzn.study.spring.jmx.MyHelloMBean"></bean>

</beans>

 

 

 

对应的main函数:

 

 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author guoliang
 * @version 创建时间:2010-11-14 下午03:50:48 类说明
 */

public class JmxTestMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-jmx.xml");

        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
 

 

 

运行该main函数,跟上一篇类似,需要在eclipse的启动参数里面加上那个那一句话:

 

-Dcom.sun.management.jmxremote=JmxTestMain

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics