JMX连接Mbean获取Tomcat信息(jconsole远程查看Mbean)

时间:2022-08-20 18:03:59

最近用JAVA写了个获取tomcat信息资源的代码,随便保存一下。

大致的步骤全在这了,可以获取到任何想要的指标:

 

首先可以用JDK提供的工具jconsole来供我们查看,这个在服务端配置下catalina.bat文件,加入以下内容:

 

  
 
 
  1. set JAVA_OPTS= -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=7999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false  

端口7999可以*更改,前提是没被系统占用。

这时就可以在jconsole里面输入远程路径和用户名密码登入了。输入命令:

  
 
 
  1. service:jmx:rmi:///jndi/rmi://192.168.133.184:7999/jmxrmi 

 

下面为获取数据代码:

  
 
 
  1. import java.lang.management.MemoryUsage; 
  2. import java.text.SimpleDateFormat; 
  3. import java.util.Date; 
  4. import java.util.Formatter; 
  5. import java.util.HashMap; 
  6. import java.util.Iterator; 
  7. import java.util.Map; 
  8. import java.util.Set; 
  9.  
  10. import javax.management.MBeanAttributeInfo; 
  11. import javax.management.MBeanInfo; 
  12. import javax.management.MBeanServerConnection; 
  13. import javax.management.ObjectInstance; 
  14. import javax.management.ObjectName; 
  15. import javax.management.openmbean.CompositeDataSupport; 
  16. import javax.management.remote.JMXConnector; 
  17. import javax.management.remote.JMXConnectorFactory; 
  18. import javax.management.remote.JMXServiceURL; 
  19.  
  20. public class test { 
  21.     /** 
  22.      * @param args 
  23.      */ 
  24.     public static void main(String[] args) { 
  25.         try { 
  26.  
  27.             String jmxURL = "service:jmx:rmi:///jndi/rmi://192.168.1.126:10090/jmxrmi";//tomcat jmx url   
  28.             JMXServiceURL serviceURL = new JMXServiceURL(jmxURL); 
  29.  
  30.             Map map = new HashMap(); 
  31.             String[] credentials = new String[] { "monitorRole""QED" }; 
  32.             map.put("jmx.remote.credentials", credentials); 
  33.             JMXConnector connector = JMXConnectorFactory.connect(serviceURL, map); 
  34.             MBeanServerConnection mbsc = connector.getMBeanServerConnection(); 
  35.  
  36.             //端口最好是动态取得   
  37.             ObjectName threadObjName = new ObjectName("Catalina:type=ThreadPool,name=http-8089"); 
  38.             MBeanInfo mbInfo = mbsc.getMBeanInfo(threadObjName); 
  39.  
  40.             String attrName = "currentThreadCount";//tomcat的线程数对应的属性值   
  41.             MBeanAttributeInfo[] mbAttributes = mbInfo.getAttributes(); 
  42.             System.out.println("currentThreadCount:" + mbsc.getAttribute(threadObjName, attrName)); 
  43.  
  44.             //heap   
  45.             for (int j = 0; j < mbsc.getDomains().length; j++) { 
  46.                 System.out.println("###########" + mbsc.getDomains()[j]); 
  47.             } 
  48.             Set MBeanset = mbsc.queryMBeans(nullnull); 
  49.             System.out.println("MBeanset.size() : " + MBeanset.size()); 
  50.             Iterator MBeansetIterator = MBeanset.iterator(); 
  51.             while (MBeansetIterator.hasNext()) { 
  52.                 ObjectInstance objectInstance = (ObjectInstance) MBeansetIterator.next(); 
  53.                 ObjectName objectName = objectInstance.getObjectName(); 
  54.                 String canonicalName = objectName.getCanonicalName(); 
  55.                 System.out.println("canonicalName : " + canonicalName); 
  56.                 if (canonicalName.equals("Catalina:host=localhost,type=Cluster")) { 
  57.                     // Get details of cluster MBeans   
  58.                     System.out.println("Cluster MBeans Details:"); 
  59.                     System.out.println("========================================="); 
  60.                     //getMBeansDetails(canonicalName);   
  61.                     String canonicalKeyPropList = objectName.getCanonicalKeyPropertyListString(); 
  62.                 } 
  63.             } 
  64.             //------------------------- system ----------------------   
  65.             ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime"); 
  66.             System.out.println("厂商:" + (String) mbsc.getAttribute(runtimeObjName, "VmVendor")); 
  67.             System.out.println("程序:" + (String) mbsc.getAttribute(runtimeObjName, "VmName")); 
  68.             System.out.println("版本:" + (String) mbsc.getAttribute(runtimeObjName, "VmVersion")); 
  69.             Date starttime = new Date((Long) mbsc.getAttribute(runtimeObjName, "StartTime")); 
  70.             SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
  71.             System.out.println("启动时间:" + df.format(starttime)); 
  72.  
  73.             Long timespan = (Long) mbsc.getAttribute(runtimeObjName, "Uptime"); 
  74.             System.out.println("连续工作时间:" + test.formatTimeSpan(timespan)); 
  75.             //------------------------ JVM -------------------------   
  76.             //堆使用率   
  77.             ObjectName heapObjName = new ObjectName("java.lang:type=Memory"); 
  78.             MemoryUsage heapMemoryUsage = MemoryUsage.from((CompositeDataSupport) mbsc.getAttribute(heapObjName, 
  79.                     "HeapMemoryUsage")); 
  80.             long maxMemory = heapMemoryUsage.getMax();//堆最大   
  81.             long commitMemory = heapMemoryUsage.getCommitted();//堆当前分配   
  82.             long usedMemory = heapMemoryUsage.getUsed(); 
  83.             System.out.println("heap:" + (double) usedMemory * 100 / commitMemory + "%");//堆使用率   
  84.  
  85.             MemoryUsage nonheapMemoryUsage = MemoryUsage.from((CompositeDataSupport) mbsc.getAttribute(heapObjName, 
  86.                     "NonHeapMemoryUsage")); 
  87.             long noncommitMemory = nonheapMemoryUsage.getCommitted(); 
  88.             long nonusedMemory = heapMemoryUsage.getUsed(); 
  89.             System.out.println("nonheap:" + (double) nonusedMemory * 100 / noncommitMemory + "%"); 
  90.  
  91.             ObjectName permObjName = new ObjectName("java.lang:type=MemoryPool,name=Perm Gen"); 
  92.             MemoryUsage permGenUsage = MemoryUsage.from((CompositeDataSupport) mbsc.getAttribute(permObjName, "Usage")); 
  93.             long committed = permGenUsage.getCommitted();//持久堆大小   
  94.             long used = heapMemoryUsage.getUsed();//   
  95.             System.out.println("perm gen:" + (double) used * 100 / committed + "%");//持久堆使用率   
  96.  
  97.             //-------------------- Session ---------------    
  98.             ObjectName managerObjName = new ObjectName("Catalina:type=Manager,*"); 
  99.             Set<ObjectName> s = mbsc.queryNames(managerObjName, null); 
  100.             for (ObjectName obj : s) { 
  101.                 System.out.println("应用名:" + obj.getKeyProperty("path")); 
  102.                 ObjectName objname = new ObjectName(obj.getCanonicalName()); 
  103.                 System.out.println("最大会话数:" + mbsc.getAttribute(objname, "maxActiveSessions")); 
  104.                 System.out.println("会话数:" + mbsc.getAttribute(objname, "activeSessions")); 
  105.                 System.out.println("活动会话数:" + mbsc.getAttribute(objname, "sessionCounter")); 
  106.             } 
  107.  
  108.             //----------------- Thread Pool ----------------   
  109.             ObjectName threadpoolObjName = new ObjectName("Catalina:type=ThreadPool,*"); 
  110.             Set<ObjectName> s2 = mbsc.queryNames(threadpoolObjName, null); 
  111.             for (ObjectName obj : s2) { 
  112.                 System.out.println("端口名:" + obj.getKeyProperty("name")); 
  113.                 ObjectName objname = new ObjectName(obj.getCanonicalName()); 
  114.                 System.out.println("最大线程数:" + mbsc.getAttribute(objname, "maxThreads")); 
  115.                 System.out.println("当前线程数:" + mbsc.getAttribute(objname, "currentThreadCount")); 
  116.                 System.out.println("繁忙线程数:" + mbsc.getAttribute(objname, "currentThreadsBusy")); 
  117.             } 
  118.  
  119.         } catch (Exception e) { 
  120.             e.printStackTrace(); 
  121.         } 
  122.     } 
  123.  
  124.     public static String formatTimeSpan(long span) { 
  125.         long minseconds = span % 1000
  126.  
  127.         span = span / 1000
  128.         long seconds = span % 60
  129.  
  130.         span = span / 60
  131.         long mins = span % 60
  132.  
  133.         span = span / 60
  134.         long hours = span % 24
  135.  
  136.         span = span / 24
  137.         long days = span; 
  138.         return (new Formatter()).format("%1$d天 %2$02d:%3$02d:%4$02d.%5$03d", days, hours, mins, seconds, minseconds) 
  139.                 .toString(); 
  140.     } 
  141.  
  142. }  

 

 

  
 
 
  1. import java.util.Iterator;    
  2. import java.util.Set;    
  3. import javax.management.Attribute;    
  4. import javax.management.MBeanInfo;    
  5. import javax.management.MBeanServerConnection;    
  6. import javax.management.MBeanServerInvocationHandler;    
  7. import javax.management.ObjectInstance;    
  8. import javax.management.ObjectName;    
  9. import javax.management.remote.JMXConnector;    
  10. import javax.management.remote.JMXConnectorFactory;    
  11. import javax.management.remote.JMXServiceURL;    
  12. public class Client {    
  13.     public static void main(String[] args) throws Exception {       
  14.         JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");       
  15.         JMXConnector jmxc = JMXConnectorFactory.connect(url, null);        
  16.         MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();      
  17.         ObjectName mbeanName = new ObjectName("chengang:name=HelloWorld");    
  18.         // 把所有Domain都打印出来    
  19.         System.out.println("Domains:---------------");       
  20.         String domains[] = mbsc.getDomains();        
  21.         for (int i = 0; i < domains.length; i++) {        
  22.             System.out.println("\tDomain[" + i + "] = " + domains[i]);     
  23.         }    
  24.         // MBean的总数    
  25.         System.out.println("MBean count = " + mbsc.getMBeanCount());    
  26.         // 对name属性的操作(属性名的第一个字母要大写)    
  27.         mbsc.setAttribute(mbeanName, new Attribute("Name""PANDA"));// 设值    
  28.         System.out.println("Name = " + mbsc.getAttribute(mbeanName, "Name"));// 取值    
  29.         // 得到proxy代理后直接调用的方式    
  30.         HelloMBean proxy = (HelloMBean) MBeanServerInvocationHandler.newProxyInstance(mbsc, mbeanName, HelloMBean.classfalse);         
  31.         proxy.printHello();         
  32.         proxy.printHello("Raymend");    
  33.         // 远程调用的方式    
  34.         mbsc.invoke(mbeanName, "printHello"nullnull);          
  35.         mbsc.invoke(mbeanName, "printHello"new Object[] { "熊猫烧香" }, new String[] { String.class.getName() });    
  36.         // 得mbean的信息    
  37.         MBeanInfo info = mbsc.getMBeanInfo(mbeanName);          
  38.         System.out.println("Hello Class: " + info.getClassName());       
  39.         System.out.println("Hello Attriber:" + info.getAttributes()[0].getName());      
  40.         System.out.println("Hello Operation:" + info.getOperations()[0].getName());    
  41.         // 得到所有的MBean的ObjectName    
  42.         System.out.println("all ObjectName:---------------");         
  43.         Set set = mbsc.queryMBeans(nullnull);        
  44.         for (Iterator it = set.iterator(); it.hasNext();) {         
  45.             ObjectInstance oi = (ObjectInstance) it.next();         
  46.             System.out.println("\t" + oi.getObjectName());         
  47.             }
  48.         // 关闭MBeanServer连接    
  49.         jmxc.close();      
  50. }    
  51. }