Skip to content

Instantly share code, notes, and snippets.

@wangzaixiang
Created December 19, 2013 09:05
Show Gist options
  • Save wangzaixiang/8036466 to your computer and use it in GitHub Desktop.
Save wangzaixiang/8036466 to your computer and use it in GitHub Desktop.
JMX Demo
package jmxdemo;
import java.io.File;
import java.util.Set;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import com.sun.tools.attach.VirtualMachine;
public class Client {
public static void main(String[] args) throws Exception {
String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
if (args.length == 0) {
System.out.println("usage: java Client pid");
System.exit(-1);
}
VirtualMachine vm = VirtualMachine.attach(args[0]);
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
System.out.println("connectorAddress = " + connectorAddress);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator
+ "management-agent.jar";
vm.loadAgent(agent);
// agent is started, get the connector address
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
System.out.println("connectorAddress = " + connectorAddress);
}
// establish connection to connector server
JMXServiceURL url = new JMXServiceURL(connectorAddress);
JMXConnector connector = JMXConnectorFactory.connect(url);
MBeanServerConnection mbeanServer = connector.getMBeanServerConnection();
ObjectName refName = new ObjectName("sample:key=major");
Set<ObjectInstance> beans = mbeanServer.queryMBeans(refName, null);
if (beans.size() == 1) {
SampleMBean fooProxy = JMX.newMBeanProxy(mbeanServer, refName, SampleMBean.class);
String result = fooProxy.getCurrentTime();
System.out.println("result = " + result);
}
}
}
package jmxdemo;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class Main {
public static void main(String[] args) throws Exception {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
mBeanServer.registerMBean(
new Sample(),
new ObjectName("sample:key=major"));
Thread.sleep(600*1000);
}
}
package jmxdemo;
public class Sample implements SampleMBean {
public String getCurrentTime() {
return String.format("%tT", System.currentTimeMillis());
}
}
package jmxdemo;
public interface SampleMBean {
String getCurrentTime();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment