一:创建maven项目,在pom.xml里面增加例如以下依赖
<dependency> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> <version>1.2.1</version> </dependency>
<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 连接就可以进入