JMX之Standard MBean

1.Standard MBean

Standard MBean(标准管理构件)是JMX管理构件中最简单的一种,只需要开发一个MBean接口,一个实现MBean接口的类,并且把他们注册到MBeanServer中就可以了。

package com.jmx.demo;

public interface HelloMBean {
	public String getName();
	
	public void setName(String name);
	
	public void helloWorld();
	
	public void helloWorld(String name);
	
	public String getTelephone();
	
}

package com.jmx.demo;

public class Hello implements HelloMBean {
	
	private String name;
	private String telephone ="1351201201";
	@Override
	public String getName() {
		return name;
	}

	@Override
	public void helloWorld() {
		System.out.println("print......"+name);

	}

	@Override
	public void helloWorld(String name) {
		System.out.println("print......."+name);

	}

	@Override
	public void setName(String name) {
		this.name = name;
		System.out.println("My value is set to "+name);

	}

	@Override
	public String getTelephone() {
		return telephone;
	}

}

注册MBean、注册需要使用的adaptor并启动JMX服务

package com.jmx.demo;

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 {
	public static void main(String[] args) throws MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
		
		//create mbean server
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		
		//create object name
		ObjectName helloName = new ObjectName("jmxBean:name=hello");
		
		//create mbean and register mbean
		server.registerMBean(new Hello(), helloName);
		
		//create adaptor, adaptor is just a form as show mbean. It has no relation to specific mbean.
		HtmlAdaptorServer adaptor  = new HtmlAdaptorServer();
		//create adaptor name
		ObjectName adaptorName = new ObjectName("jmxAdaptor:name=adaptor,port=5050");
		//register adaptor and adaptor name
		server.registerMBean(adaptor, adaptorName);
		
		adaptor.setPort(9999);
		adaptor.start();
		System.out.println("....................jmx server start....................");
		
	}
}

启动服务后,可以访问http://localhost:9999/ ,就可以看到JMX提供的HTMLAdaptor的MBean的管理界面了

JMX之Standard MBean_第1张图片

点击我们创建的那个MBean后,可以看到MBean的基本信息,包括属性、方法等。

JMX之Standard MBean_第2张图片

点击helloWorld这个方法,就会调用到MBean的实现了


控制台输出如下:


点击带参数的方法,并且输入一个参数


控制台输出如下:





你可能感兴趣的:(J2EE,jmx)