import javax.management.*;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
/**
* This class represents a JMX client that connects to a remote JMX server to retrieve and print
* attribute values of a specified MBean (Managed Bean) object at regular intervals.
*/
public class JMXClientJMXOneMetric {
/**
* The main entry point of the JMX client application.
*
* @param args Command-line arguments. Expects two arguments: <ObjectName> and <DelayInMillis>.
* <ObjectName> specifies the target MBean's ObjectName, and <DelayInMillis> is
* the delay between metric checks in milliseconds.
* Example: java JMXClient metrics:name=com.hivemq.jvm.memory.heap.used 2000
* @throws Exception If there are errors in the JMX connection or attribute retrieval.
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java JMXClient <ObjectName> <DelayInMillis>");
System.err.println("Example: java JMXClient metrics:name=com.hivemq.jvm.memory.heap.used 2000");
System.exit(1);
}
// Parse command-line arguments
String objectNameStr = args[0];
long delayInMillis = Long.parseLong(args[1]);
// Define the JMX service URL for connecting to the remote JMX server
String jmxUrl = "service:jmx:rmi:///jndi/rmi://localhost:9010/jmxrmi";
JMXServiceURL serviceURL = new JMXServiceURL(jmxUrl);
JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
MBeanServerConnection connection = connector.getMBeanServerConnection();
// Define the ObjectName based on the command-line argument
ObjectName mbeanName = new ObjectName(objectNameStr);
// Run indefinitely with the specified delay between checks
while (true) {
// Fetch and print the metric value
Object metricValue = connection.getAttribute(mbeanName, "Value");
System.out.println(objectNameStr + " " + metricValue);
// Sleep for the specified delay before the next check
Thread.sleep(delayInMillis);
}
}
} |