JMX最简单的一个例子
package com;public interface HelloMBean {public String getName();public void setName(String name);public void printHello();public void printHello(String whoName);}
?
?
package com;public class Hello implements HelloMBean {private String name;public String getName() {// TODO Auto-generated method stubreturn name;}public void printHello() {// TODO Auto-generated method stubSystem.out.println("hello world"+name);}public void printHello(String whoName) {// TODO Auto-generated method stubSystem.out.println("hello,"+whoName);}public void setName(String name) {// TODO Auto-generated method stubthis.name=name;}}
?
?
package com;import java.lang.management.ManagementFactory;import javax.management.InstanceAlreadyExistsException;import javax.management.MBeanRegistrationException;import javax.management.MBeanServer;import javax.management.MalformedObjectNameException;import javax.management.NotCompliantMBeanException;import javax.management.ObjectName;import com.sun.jdmk.comm.HtmlAdaptorServer;public class HelloAgent {/** * @param args * @throws NullPointerException * @throws MalformedObjectNameException * @throws NotCompliantMBeanException * @throws MBeanRegistrationException * @throws InstanceAlreadyExistsException * @throws Exception */public static void main(String[] args) throws MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, Exception {//先创建了一个MBeanServer,用来做MBean的容器 //MBeanServer server = MBeanServerFactory.createMBeanServer(); MBeanServer server=ManagementFactory.getPlatformMBeanServer();//将Hello这个类注入到MBeanServer中,注入需要创建一个ObjectName类 //chengang:name=HelloWorld的名字是有一定规则的,格式为:“域名:name=MBean名称”,域名和MBean名称都可以任意取。 ObjectName helloName= new ObjectName("yu:name=Hhaha"); Hello hello = new Hello(); server.registerMBean(hello,helloName); //创建一个AdaptorServer,这个类将决定MBean的管理界面,这里用最普通的Html型界面。AdaptorServer其实也是一个MBean。 ObjectName adapterName = new ObjectName("HelloAgent:name=htmladapter,port=8082"); HtmlAdaptorServer adapter = new HtmlAdaptorServer(); server.registerMBean(adapter, adapterName); adapter.start(); System.out.println("start"); for(int i =0; i<100;i++){ System.out.println(hello.getName()); Thread.sleep(6000); }}}?