效果
示例
下面展示一个完整的代码
首先定义一个MBean接口
package com.xuanyuv.demo.jmx;
/**
* 定义一个MBean接口
* @create Jul 16, 2012 2:14:07 PM
* @author 玄玉(https://www.xuanyuv.com/)
*/
public interface UserActionMBean {
/**
* 用户的年龄
*/
void setAge(int age);
int getAge();
/**
* 用户的名字
*/
void setName(String name);
String getName();
/**
* 获取用户资料
*/
String getUserInfo();
}
然后再实现这个MBean接口
package com.xuanyuv.demo.jmx;
/**
* 实现MBean接口
* @create Jul 16, 2012 2:14:24 PM
* @author 玄玉(https://www.xuanyuv.com/)
*/
class UserAction implements UserActionMBean {
private int age;
private String name;
@Override
public void setAge(int age) {
this.age = age;
}
@Override
public int getAge() {
return age;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String getUserInfo() {
return "This is UserAction MBean, its name is " + this.name + ", age is " + this.age;
}
}
最后启动JMX监控
package com.xuanyuv.demo.jmx;
import com.sun.jdmk.comm.HtmlAdaptorServer;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.swing.JDialog;
import java.lang.management.ManagementFactory;
/**
* 启动JMX监控
* <ul>
* <li>用法:运行该程序,然后win+R-->cmd-->jconsole,[本地]选择这里运行的程序,然后进入MBean面板页</li>
* <li>注意:标准MBean名称必需是在待监控的类名后面加上MBean,且待监控的类和MBean接口必需在同一包下</li>
* </ul>
* @create Jul 16, 2012 2:12:36 PM
* @author 玄玉(https://www.xuanyuv.com/)
*/
public class MainMonitor {
public static void main(String[] args) throws Exception {
//MBeanServer是MBean的容器,可以通过多种方式获得MBeanServer的实例
//不能在jconsole中使用
//MBeanServer mbserver = MBeanServerFactory.createMBeanServer();
//可以在jconsole中使用
MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
//创建MBean(注意UserActionMBean必须是public)
UserActionMBean userAction = new UserAction();
//将MBean注册到MBeanServer中
mbserver.registerMBean(userAction, new ObjectName("MyAppMBean:name=userAction"));
//启用HTML协议适配器,使之能够通过浏览器访问MBean,地址为http://127.0.0.1:9999
//注意HtmlAdaptorServer需要引入jmxtool.jar
//Maven坐标为<dependency groupId="com.sun.jdmk" artifactId="jmxtools" version="1.2.1"/>
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);
}
}