JMX简单例子

一:创建maven项目,在pom.xml里面加入如下依赖

<dependency>
	<groupId>com.sun.jdmk</groupId>
	<artifactId>jmxtools</artifactId>
	<version>1.2.1</version>
</dependency>


由于该依赖在默认的maven中央仓库无法下载,所以,还必须加入如下仓库

<repositories>
	<repository>
		<id>jboss</id>
		<url>http://repository.jboss.org/maven2/</url>
	</repository>
</repositories>

二:创建一个MBean的接口


package com.lala.jmx;

public interface ConfigMBean 
{
	public String getBind();
	
	public void setBind(String bind);
	
	public Integer getPort();
	
	public void setPort(Integer port);
}

实现类:

package com.lala.jmx;

public class Config implements ConfigMBean 
{
	private String bind;
	private Integer port;

	public String getBind() {
		return bind;
	}

	public void setBind(String bind) {
		this.bind = bind;
	}

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}
}

创建Agent类

package com.lala.jmx;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

import com.sun.jdmk.comm.HtmlAdaptorServer;

public class ConfigAgent
{
	public static void main(String[] args)throws Exception
	{
		int port = 8282;
		MBeanServer server = MBeanServerFactory.createMBeanServer();
        ObjectName configName = new ObjectName("config:name=configure");
        server.registerMBean(new Config(), configName);
        ObjectName adapterName = new ObjectName("config:name=htmladapter");
        HtmlAdaptorServer adapter = new HtmlAdaptorServer();
        server.registerMBean(adapter, adapterName);
        adapter.setPort(port);
        adapter.start();
        System.out.println("server start on port "+port+" .....");
	}
}

注意:

config:name=configure  的名字是有一定规则的,格式为:“域名:name=MBean名称”,域名和MBean名称都可以任意取

最后,在浏览器上访问

http://127.0.0.1:8282   单击 config:name=configure 连接即可进入

你可能感兴趣的:(JMX简单例子)