我有一个关于 JMX 的简单类:Interface HelloMBean:
public interface HelloMBean {
public void sayHello();
public String getName();
public void setName(String name);
public String conCat(String s1, String s2);
}
类 Hello 从接口 HelloMBean 实现:
import javax.management.AttributeChangeNotification;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
public class Hello extends NotificationBroadcasterSupport implements HelloMBean {
private String m_name;
@Override
public void sayHello() {
System.out.print("I say hello");
}
@Override
public String getName() {
return null;
}
@Override
public void setName(String name) {
Notification n = new AttributeChangeNotification(
this, 0,
System.currentTimeMillis(),
"My name is changed",
"setName", "String", m_name, name);
sendNotification(n);
m_name = name;
}
@Override
public String conCat(String s1, String s2) {
return null;
}
}
然后,我创建了一个类客户端:
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class HelloClient {
public static void main(String[] args) throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:7271/Hello");
JMXConnector cn = JMXConnectorFactory.connect(url);
MBeanServerConnection msc = cn.getMBeanServerConnection();
ObjectName helloObjName = new ObjectName("com:service=Hello1");
HelloMBean hello = JMX.newMBeanProxy(msc, helloObjName, HelloMBean.class);
hello.sayHello();
System.out.println(hello.conCat("I am", " a hello mbean"));
Thread.sleep(Long.MAX_VALUE);
}
}
和类服务器:
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
public class HelloMain {
public static void main(String[] args) throws Exception {
MBeanServer ms = ManagementFactory.getPlatformMBeanServer();
ObjectName helloMBName = new ObjectName("com:service=Hello1");
Hello hello = new Hello();
ms.registerMBean(hello, helloMBName);
JMXServiceURL url = new JMXServiceURL(
"service:jmx:rmi:///jndi/rmi://localhost:7271/Hello");
JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, ms);
cs.start();//
Thread.sleep(Long.MAX_VALUE);
}
}
使用 rmiregistry 7271 之后。我使用 JMX 创建了简单的客户端和服务器。但我无法将 JMX 与 Spring 集成(JMX 由 Spring 处理)。我尝试过但不成功。有什么解决办法吗??