1、MBean接口
public interface TestJMXMBean {
public String sayHello();
public String getName();
}
2、MBean实现
public class TestJMX implements TestJMXMBean {
public String sayHello() {
System.out.println("Hello!!!");
return "Hello!!!";
}
public String getName() {
return "caililiang";
}
}
3、MBean代理
import java.lang.management.ManagementFactory;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
public class TestJMXAgent {
public static void main(String[] args) {
TestJMXAgent agent = new TestJMXAgent();
try {
agent.startMBean(9999);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public static void startMBean(int port){
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName testMBeanName = new ObjectName("jmxBean:name=TestJMX");
server.registerMBean(new TestJMX(), testMBeanName);
LocateRegistry.createRegistry(port);
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:"+port+"/jmxrmi/TestJMX");
JMXConnectorServer jcs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
jcs.start();
System.out.println("service:jmx:rmi:///jndi/rmi://localhost:"+port+"/jmxrmi/TestJMX ----start");
} catch (Exception e) {
e.printStackTrace();
}
}
4、MBean客户端代码
import java.io.IOException;
import java.net.MalformedURLException;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class TestJMXClient {
public static void main(String[] args) {
TestJMXClient c = new TestJMXClient();
try {
String name =c.getName();
} catch (MalformedObjectNameException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getName() throws IOException, MalformedObjectNameException, NullPointerException{
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi/TestJMX");
JMXConnector jmxc = JMXConnectorFactory.connect(url,null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
ObjectName mbeanName = new ObjectName("jmxBean:name=TestJMX");
TestJMXMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbsc, mbeanName, TestJMXMBean.class, false);
String name = proxy.getName();
if(jmxc!=null){jmxc.close();}
return name;
}
}