[Java]JMX

在JVM中有一些常用的MBeans,可以写个代码获取到:

public class Test {
    public static void main(String[] args) throws Exception {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        Set instances = server.queryMBeans(null, null);
        Iterator iterator = instances.iterator();
        while (iterator.hasNext()) {
            ObjectInstance instance = (ObjectInstance) iterator.next();
            System.out.println("MBean Found:");
            System.out.println("Class Name:\t" + instance.getClassName());
            System.out.println("Object Name:\t" + instance.getObjectName());
            System.out.println("****************************************");
        }
    }
}

根据列表,我们就能通过MBean来获取想要的信息了,比如获取Code Cache的大小:

public class TestMBean {
    final static String pid               = "6228";
    final static String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";

    public static void main(String[] args) throws Exception {
        VirtualMachine vm = VirtualMachine.attach(pid);
        JMXConnector connector = null;
        String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);

        String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib" + File.separator
                + "management-agent.jar";
        vm.loadAgent(agent);

        connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
        JMXServiceURL url = new JMXServiceURL(connectorAddress);
        connector = JMXConnectorFactory.connect(url);
        MBeanServerConnection mbeanConn = connector.getMBeanServerConnection();
        ObjectName name = new ObjectName("java.lang:type=MemoryPool,name=Code Cache");
        System.out.println(mbeanConn.getAttribute(name, "Usage"));

        if (connector != null) {
            connector.close();
        }
        vm.detach();
    }
}

实际上通过ObjectName("java.lang:type=MemoryPool,name=Code Cache")得到的类为:

sun.management.MemoryPoolImpl

而在getAttribute(name, "Usage")的时候对应调用的方法为:

public java.lang.management.MemoryUsage getUsage(){}
其他MBean的用法和这个类似。

















[Java]JMX,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。