我来做一回技术控,这部分内容也是简单的API调用例子而已,做一回技术控,发点小骚文,不过你看了,也许知道JConsole是怎么做出来的了,呵呵!
先不用管他干什么,代码运行后,自己改改自然知道做什么的。
例子全部应该都可以运行,使用者,拷贝回去就基本可以用了,无需其他内容的支持,有部分代码对JDK的版本有要求,例如在使用:ThreadMXBean.getThreadAllocatedBytes(id),这个是在JDK 6 update 25中开始支持的,而且在JDK 1.6中获取出来还有问题不少。
我先写了个简单的工具类:
import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.Set; import javax.management.AttributeNotFoundException; import javax.management.BadAttributeValueExpException; import javax.management.BadBinaryOpValueExpException; import javax.management.BadStringOperationException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidApplicationException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.management.RuntimeMBeanException; public class JMXUtils { private final static MBeanServer DEFAULT_MBEAN_SERVER = ManagementFactory .getPlatformMBeanServer(); public static long getYongGC() { return getYoungGC(DEFAULT_MBEAN_SERVER); } public static long getFullGC() { return getFullGC(DEFAULT_MBEAN_SERVER); } public static long findLoadedClass() { return findLoadedClass(DEFAULT_MBEAN_SERVER); } public static long getYoungGC(MBeanServerConnection mbeanServer) { try { ObjectName objectName; if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ParNew"))) { objectName = new ObjectName("java.lang:type=GarbageCollector,name=ParNew"); } else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=Copy"))) { objectName = new ObjectName("java.lang:type=GarbageCollector,name=Copy"); } else { objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS Scavenge"); } return (Long) mbeanServer.getAttribute(objectName , "CollectionCount"); } catch (Exception e) { throw new RuntimeException(e); } } public static long getFullGC(MBeanServerConnection mbeanServer) { try { ObjectName objectName; if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"))) { objectName = new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"); } else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact"))) { objectName = new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact"); } else { objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS MarkSweep"); } return (Long) mbeanServer.getAttribute(objectName , "CollectionCount"); } catch (Exception e) { throw new RuntimeException(e); } } public static long findLoadedClass(MBeanServerConnection mBeanServer) { try { return (Long) (mBeanServer.getAttribute(new ObjectName( "java.lang:type=ClassLoading"), "TotalLoadedClassCount")); } catch (Exception e) { throw new RuntimeException(e); } } public static void traceOneDomain(String doMain, MBeanServerConnection mBeanServer) throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException { Set<ObjectInstance> set = mBeanServer.queryMBeans(new ObjectName(doMain + ":*"), new QueryExp() { private static final long serialVersionUID = 1L; @Override public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { return true; } @Override public void setMBeanServer(MBeanServer s) {} }); for (ObjectInstance objectInstance : set) { System.out.println("\t\t\t" + objectInstance.getObjectName() + "\t" + objectInstance.getClassName()); traceMebeanInfo(mBeanServer, objectInstance.getObjectName()); } } public static void traceMebeanInfo(MBeanServerConnection mBeanServer, ObjectName objectName) throws IntrospectionException, InstanceNotFoundException, MalformedObjectNameException, ReflectionException, AttributeNotFoundException, MBeanException, IOException { MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objectName); MBeanAttributeInfo[] mBeanAttributes = mBeanInfo.getAttributes(); System.out.println("\t\t\tMBeanInfos : "); for (MBeanAttributeInfo mBeanAttribute : mBeanAttributes) { try { System.out.println("\t\t\t\t\t" + mBeanAttribute.getName() + "\t" + mBeanAttribute.getType() + "\tvalue = >" + mBeanServer.getAttribute(objectName, mBeanAttribute.getName())); } catch (RuntimeMBeanException e) { if (e.getCause() instanceof UnsupportedOperationException) { System.out.println("\t\t\t\t\t" + mBeanAttribute.getName() + "\t" + mBeanAttribute.getType() + "\tvalue = > value not supported"); } } } } public static void traceAll(MBeanServerConnection mBeanServer) throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException { System.out.println("MBean count = " + mBeanServer.getMBeanCount()); String[] domains = mBeanServer.getDomains(); for (String domain : domains) { System.out.println("\tbegin trace domain -> " + domain); traceOneDomain(domain, mBeanServer); } } }
这个类写好后,我们就可以写点小测试代码了,呵呵!
那么首先来写个遍历所有的参数列表,层次结构为3层:
MBeanServer -> DoMain -> MBean -> MBeanAttributeInfo 但是写好那个Util后调用就简单了:
import java.io.IOException; import java.lang.management.ManagementFactory; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.MBeanException; import javax.management.MalformedObjectNameException; import javax.management.ReflectionException; public class MBeanServerTest { public static void main(String[] args) throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException { // System.gc(); // System.out.println(JMXUtils.getYongGC()); // System.out.println(JMXUtils.getFullGC()); JMXUtils.traceAll(ManagementFactory.getPlatformMBeanServer()); } }
结果很多,不同的OS,不同的JVM配置,结果也会有所区别,大家可以自己书出来看看,这里注意里面的ObjectName,通过MBeanServer直接获取里面的参数值,比较好用,尤其是RMI的时候,这个trace不太好用,因为远程可能有些类,本地没有,但是参数值是可以获取到的,所以需要知道名称是比较好的。
远程的输出,我们简单来写一段代码:
import java.io.IOException; import java.util.HashMap; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.MBeanException; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; public class MBeanServerRemoteTest { /** * 远程地址需要开启: * -Dcom.sun.management.jmxremote * -Dcom.sun.management.jmxremote.port=9000 * -Dcom.sun.management.jmxremote.authenticate=true */ final static String RMI_URL = "service:jmx:rmi:///jndi/rmi://xxx.xxx.xxx.xxx:9000/jmxrmi"; public static void main(String []args) throws IOException, MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException { JMXServiceURL serviceURL = new JMXServiceURL(RMI_URL); JMXConnector jmxc = JMXConnectorFactory.connect(serviceURL , new HashMap<String , Object>() { private static final long serialVersionUID = 1L; { put(JMXConnector.CREDENTIALS , new String[] {"controlRole" , "FUCK"}); } }); MBeanServerConnection mBeanServer = jmxc.getMBeanServerConnection(); System.out.println("MBean count = " + mBeanServer.getMBeanCount()); String[] domains = mBeanServer.getDomains(); for (String doMain : domains) { System.out.println("============>" + doMain); } System.out.println(JMXUtils.getYoungGC(mBeanServer)); System.out.println(JMXUtils.getFullGC(mBeanServer)); System.out.println(mBeanServer.getAttribute(new ObjectName("JMImplementation:type=MBeanServerDelegate"), "ImplementationVersion")); System.out.println(mBeanServer.getAttribute(new ObjectName("java.lang:type=Runtime"), "BootClassPath")); //其余的可以自己遍历出来 } }
这两个出来了,其实JMX还提供了些简单的,默认的MXBean,可以直接使用,我们简单也写下这些demo,可以拿去自己玩哈。
===》ClassLoadingMXBean:
import java.lang.management.ClassLoadingMXBean; import java.lang.management.ManagementFactory; public class ClassLoadingMXBeanTest { public static void main(String []args) { ClassLoadingMXBean classLoadingMXBean = ManagementFactory.getClassLoadingMXBean(); System.out.println(classLoadingMXBean.getLoadedClassCount()); System.out.println(classLoadingMXBean.getTotalLoadedClassCount()); System.out.println(classLoadingMXBean.getUnloadedClassCount()); System.out.println(classLoadingMXBean.isVerbose()); } }
===》CompilationMXBean
import java.lang.management.CompilationMXBean; import java.lang.management.ManagementFactory; public class CompilationMXBeanTest { public static void main(String []args) { CompilationMXBean mxBean = ManagementFactory.getCompilationMXBean(); System.out.println(mxBean.getTotalCompilationTime()); System.out.println(mxBean.getName()); System.out.println(mxBean.isCompilationTimeMonitoringSupported()); } }
===》MemoryManagerMXBean
import java.lang.management.ManagementFactory; import java.lang.management.MemoryManagerMXBean; import java.util.List; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.ReflectionException; public class MemoryManagerMXBeanTest { public static void main(String []args) throws IntrospectionException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); System.gc(); List<MemoryManagerMXBean> list = ManagementFactory.getMemoryManagerMXBeans(); for(MemoryManagerMXBean memoryManagerMXBean : list) { System.out.println(memoryManagerMXBean.getName()); System.out.println(memoryManagerMXBean.getObjectName()); MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(memoryManagerMXBean.getObjectName()); MBeanAttributeInfo[] mBeanAttributes = mBeanInfo.getAttributes(); for(MBeanAttributeInfo mBeanAttribute : mBeanAttributes) { System.out.println("=============>" + mBeanAttribute.getName() + "\t" + mBeanAttribute.getType()); System.out.println("=============value = >" + mBeanServer.getAttribute(memoryManagerMXBean.getObjectName(), mBeanAttribute.getName())); } /*String []poolNames = memoryManagerMXBean.getMemoryPoolNames(); for(String poolName : poolNames) { System.out.println("\t" + poolName); }*/ } } }
===》MemoryMXBean
import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; public class MemoryMXBeanTest { public static void main(String []args) { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); //memoryMXBean.gc(); System.out.println(memoryMXBean.getHeapMemoryUsage()); System.out.println(memoryMXBean.getObjectPendingFinalizationCount()); System.out.println(memoryMXBean.getNonHeapMemoryUsage()); } }
===》MemoryPoolMXBean
import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.util.List; public class MemoryPoolMXBeanTest { public static void main(String[] args) { List<MemoryPoolMXBean> list = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean memoryPoolMXBean : list) { System.out.println(memoryPoolMXBean.getName() + memoryPoolMXBean.getCollectionUsage() + "\n\nPeakUsage:\t\t" + memoryPoolMXBean.getPeakUsage() + "\n\nUsage:\t\t" + memoryPoolMXBean.getUsage()); /* * + memoryPoolMXBean.getUsageThreshold() + "\t" + * memoryPoolMXBean.getUsageThresholdCount() + * "\t\n\nCollectionUsage:\t\t" * * + memoryPoolMXBean.getType() + "\t" */ // memoryPoolMXBean.getCollectionUsageThreshold() + "\t" // memoryPoolMXBean.getCollectionUsageThresholdCount() + "\t" ); // String []memoryManagerNames = // memoryPoolMXBean.getMemoryManagerNames(); /* * for(String memoryManagerName : memoryManagerNames) { * System.out.println("\t\t\t\t" + memoryManagerName); } */ } } }
===》OperatingSystemMXBean
import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; public class OperatingSystemMXBeanTest { public static void main(String []args) { OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean(); System.out.println(mxBean.getArch()); System.out.println(mxBean.getAvailableProcessors()); System.out.println(mxBean.getName()); System.out.println(mxBean.getSystemLoadAverage()); System.out.println(mxBean.getVersion()); } }
===》RuntimeMXBean
import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; public class RuntimeMXBeanTest { public static void main(String []args) { RuntimeMXBean runTimeMXBean = ManagementFactory.getRuntimeMXBean(); System.out.println(runTimeMXBean.getBootClassPath()); System.out.println(runTimeMXBean.getClassPath()); System.out.println(runTimeMXBean.getLibraryPath()); System.out.println(runTimeMXBean.getManagementSpecVersion()); System.out.println(runTimeMXBean.getName()); System.out.println(runTimeMXBean.getSpecName()); System.out.println(runTimeMXBean.getSpecVendor()); System.out.println(runTimeMXBean.getStartTime()); System.out.println(runTimeMXBean.getUptime()); System.out.println(runTimeMXBean.getVmName()); System.out.println(runTimeMXBean.getVmVendor()); System.out.println(runTimeMXBean.getVmVersion()); System.out.println(runTimeMXBean.getInputArguments()); System.out.println(runTimeMXBean.getSystemProperties()); } }
===》ThreadMXBean
import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import com.sun.management.ThreadMXBean; //import sun.management.VMOptionCompositeData; //import com.sun.management.VMOption; //import java.lang.management.ManagementFactory; public class ThreadMXBeanTest { public static void main(String []args) { ThreadMXBean thredMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean(); long []ids = thredMXBean.getAllThreadIds(); for(long id : ids) { System.out.println(id + "\t" + thredMXBean.getThreadAllocatedBytes(id) + "\t" + thredMXBean.getThreadInfo(id)); } System.out.println(thredMXBean.getCurrentThreadCpuTime()); System.out.println(thredMXBean.getCurrentThreadUserTime()); System.out.println(thredMXBean.getDaemonThreadCount()); System.out.println(thredMXBean.getPeakThreadCount()); System.out.println(thredMXBean.getThreadCount()); System.out.println(thredMXBean.getTotalStartedThreadCount()); System.out.println("==========================>"); displayThreadInfos(thredMXBean , ids); } private static void displayThreadInfos(ThreadMXBean thredMXBean , long []ids) { ThreadInfo []threadInfos = thredMXBean.getThreadInfo(ids); for(ThreadInfo thread : threadInfos) { System.out.println(thread.getThreadName() + "\t" + thread.getLockOwnerId() + "\t" + thread.getThreadState() + "\t" + thread.getBlockedCount() + "\t" + thread.getBlockedTime() ); } } }