[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的使用方法和这个类似。
---------- ---------- ---------- ---------- ----------风格线---------- ---------- ---------- ---------- ----------
假设系统的MBean不能满足须要,那么我们能够自定义MBean,比方标准的MBean例如以下:
// 标准的MBean有几个限制:1、必须实现接口 2、必须有public类型的构造函数 3、命名规则 public class My implements MyMBean { public String getHello() { return "hello world"; } } public interface MyMBean { public String getHello(); }接下来能够将这个MBean增加MBeanServer:
public class Test { public static final void main(String[] args) throws Exception { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName("com.wszt:type=MyMBean"); mBeanServer.createMBean("My", objectName); } }
attach&用法和上面的一样,不赘述。除了标准的MBean还有Dynamic MBean、Model Bean、Open MBean,用法类似。
---------- ---------- ---------- ---------- ----------风格线---------- ---------- ---------- ---------- ----------
简单来看JMX是一个JVM的管理框架,MBean是对资源的封装,然后后AGENT来进行包装,最后有接口对外提供以方便使用,看下图: