首页 > 代码库 > [Java]JMX
[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的用法和这个类似。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。