(一)注册一个MBean
/**
* 注册新的MBean
*/
@Test
public void registerMBean() {
// 获取当前虚拟机使用的 MBean服务器
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
// 注册一个MBean
server.registerMBean(new HelloWorld(), new ObjectName("domain1:key1=val1"));
// 再注册一个MBean
server.registerMBean(new HelloWorld(), new ObjectName("domain1:key2=val2"));
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
| MalformedObjectNameException e) {
e.printStackTrace();
}
}
(二)注册一个JMX端口
/**
* 注册一个新的端口号用于JMX连接
* @throws Exception
*/
@Test
public void restartServer() throws Exception {
// 新启用一个端口号用于JMX连接
LocateRegistry.createRegistry(9999);
JMXConnectorServer jcs = JMXConnectorServerFactory.newJMXConnectorServer(
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi"),
null,
ManagementFactory.getPlatformMBeanServer());
jcs.start();
}
(三)客户端代码
/**
* 客户端代码
* @throws Exception
*/
@Test
public void mbeanClient() throws Exception {
//connect JMX
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
JMXConnector connector = JMXConnectorFactory.connect(url,null);
// 获取JMX连接
MBeanServerConnection conn = connector.getMBeanServerConnection();
// 获取所有域名
String domains[] = conn.getDomains();
for (int i = 0; i < domains.length; i++) {
System.out.println("Domain[" + i +"] = " + domains[i]);
}
// 获取 MBean的个数
System.out.println("MBean count = " + conn.getMBeanCount());
// 获取所有MBean
Set<ObjectInstance> set = conn.queryMBeans(null, null);
for (Iterator<ObjectInstance> it = set.iterator(); it.hasNext();) {
ObjectInstance oi = it.next();
System.out.println(oi.getObjectName());
}
ObjectName name = new ObjectName("domain1:key1=val1");
// 获取一个ObjectName对应的基本信息:MBeanInfo
MBeanInfo info = conn.getMBeanInfo(name);
System.out.println("Class:" + info.getClassName());
System.out.println("Attribute:" + info.getAttributes()[0].getName());
System.out.println("Operation:" + info.getOperations()[0].getName());
// 修改MBean属性的方式(一)
conn.setAttribute(name, new Attribute("Greeting", "JOHNLIUISMINE"));
conn.getAttribute(name, "Greeting");
// 修改MBean属性的方式(二)通过动态代理 ObjectName
HelloWorldMBean proxy = (HelloWorldMBean) MBeanServerInvocationHandler.newProxyInstance(conn, name, HelloWorldMBean.class, false);
proxy.setGreeting("nice to meet u client");
proxy.getGreeting();
// 修改MBean属性的方式(三)通过invoke
System.out.println(conn.invoke(name, "printGreeting", null, null));
// 关闭连接
connector.close();
}
网友评论