直接看代码。。
首先定义一个MBean接口
package com.jadyer.jmx; /** * 定义一个MBean接口 * @create Jul 16, 2012 2:14:07 PM * @author 玄玉(http://blog.csdn/net/jadyer) */ public interface UserActionMBean { /** * 用户的名字 */ public void setName(String name); public String getName(); /** * 用户的年龄 */ public void setAge(int age); public int getAge(); /** * 获取用户资料 */ public String getUserInfo(); }
package com.jadyer.jmx; import com.jadyer.jmx.UserActionMBean; /** * 实现MBean接口 * @create Jul 16, 2012 2:14:24 PM * @author 玄玉(http://blog.csdn/net/jadyer) */ public class UserAction implements UserActionMBean { public String name; public int age; @Override public int getAge() { return age; } @Override public String getName() { return name; } @Override public void setAge(int age) { this.age = age; } @Override public void setName(String name) { this.name = name; } @Override public String getUserInfo() { return "This is UserAction MBean, its name is " + this.name + ", age is " + this.age; } }
最后启动JMX监控
package com.jadyer.jmx; import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.swing.JDialog; import com.sun.jdmk.comm.HtmlAdaptorServer; /** * 启动JMX监控 * @see 用法:运行该程序,然后win+R---cmd---jconsole启动JConsole的图形界面 * @see 用法:启动JConsole后,在"本地"中选择这里运行的程序,然后进入MBean面板页 * @see 补充:由于这里启用了HTML协议适配器,因此也可以在浏览器中执行如同JConsole的操作:http://127.0.0.1:9999 * @see 注意:标准MBean名称必需是在待监控的类名后面加上"MBean",且待监控的类和MBean接口必需在同一包下 * @see 另附:JMX指南:http://oss.org.cn/ossdocs/java/jmx/jmx.html * @create Jul 16, 2012 2:12:36 PM * @author 玄玉(http://blog.csdn/net/jadyer) */ public class MainMonitor { public static void main(String[] args) throws Exception { //MBeanServer是MBean的容器,可以通过多种方式获得MBeanServer的实例 //MBeanServer mbserver = MBeanServerFactory.createMBeanServer(); //不能在jconsole中使用 MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer(); //可在jconsole中使用 //创建MBean UserActionMBean userAction = new UserAction(); //将MBean注册到MBeanServer中 mbserver.registerMBean(userAction, new ObjectName("MyAppMBean:name=userAction")); //创建适配器,使之能够通过浏览器访问MBean....注意HtmlAdaptorServer.class位于jmxtool.jar中,需额外引入 HtmlAdaptorServer adapter = new HtmlAdaptorServer(); adapter.setPort(9999); mbserver.registerMBean(adapter, new ObjectName("MyAppMBean:name=htmlAdapter,port=9999")); adapter.start(); //为了演示保持程序处于运行状态,创建一个图形窗口 JDialog dialog = new JDialog(); dialog.setName("jmx test"); dialog.setVisible(true); } }