Connect to a JMX server and query an MBean attribute

Here is some sample code to connect to a JMX server and query an MBean attribute.

// Connect to JMX Server.
JMXServiceURL u = new JMXServiceURL(   "service:jmx:rmi:///jndi/rmi://HOSTNAME:PORT/jmxrmi");
JMXConnector c = JMXConnectorFactory.connect(u);

// Get an MBeanServerConnection on the remote VM.
final MBeanServerConnection remote = c.getMBeanServerConnection();

// Construct the fully qualified name of the bean.
ObjectName beanName = new ObjectName("APPNAME:type=BEANTYPE,name=BEANNAME");

// Query an attribute on the MBean.
System.out.println(remote.getAttribute(beanName, "ATTRIBUTENAME"));;

The code is simpler if you are running it from the same container within which the beans are being registered.

// If you are running code within the same container as the beans are
// being registered from, it is much easier to get the connection.
MBeanServer mbsvr = MBeanServerFactory.newMBeanServer();

// And the bean name is also much simpler.
ObjectName beanName = new ObjectName(mbsvr.getDefaultDomain() + ":type=BEANTYPE,name=BEANNAME");

// Query an attribute on the MBean.
System.out.println(remote.getAttribute(beanName, "ATTRIBUTENAME"));;

Pages that will help you learn more are below.

Popular Posts