2012-02-09 45 views
4

是否有可能使用JMX API獲取tomcat服務器的內存使用情況統計信息。哪個Mbean可以提供給我這個信息?我停留在對象名的形成,下面的代碼如何使用JMX API獲取tomcat 7的內存使用情況?

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2020/jmxrmi"); 
JMXConnector jmxc = JMXConnectorFactory.connect(url); 
MBeanServerConnection server = jmxc.getMBeanServerConnection(); 

    Object o = jmxc.getMBeanServerConnection().getAttribute(
      new ObjectName("-----"); 

奇蹟JConsole的是如何繪製的圖形內存,任何指針的源代碼?

回答

4
MBeanServer connection = ManagementFactory.getPlatformMBeanServer(); 
Set<ObjectInstance> set = connection.queryMBeans(new ObjectName("java.lang:type=Memory"), null); 
ObjectInstance oi = set.iterator().next(); 
// replace "HeapMemoryUsage" with "NonHeapMemoryUsage" to get non-heap mem 
Object attrValue = connection.getAttribute(oi.getObjectName(), "HeapMemoryUsage"); 
if(!(attrValue instanceof CompositeData)) { 
    System.out.println("attribute value is instanceof [" + attrValue.getClass().getName() + 
      ", exitting -- must be CompositeData."); 
    return; 
} 
// replace "used" with "max" to get max 
System.out.println(((CompositeData)attrValue).get("used").toString()); 
+0

上述一些鏈接代碼是從jvm返回一個常量指標,而不是應用程序明智 – sanre6 2012-02-10 01:14:23

+0

我在閱讀有關複合數據類型後瞭解您的代碼,謝謝 – sanre6 2012-02-14 04:19:17

+0

它的工作原理!謝謝! – Gaucho 2013-02-08 11:13:49

1

示例代碼

列表memBeans = //獲得的mbeans 的列表(迭代器I = memBeans.iterator(); i.hasNext();){

MemoryPoolMXBean mpool = (MemoryPoolMXBean)i.next(); 
MemoryUsage usage = mpool.getUsage(); 

String name = mpool.getName();  
float init = usage.getInit()/1000; 
float used = usage.getUsed()/1000; 
float committed = usage.getCommitted()/1000; 
float max = usage.getMax()/1000; 
float pctUsed = (used/max)*100; 
float pctCommitted = (committed/max)*100; 

}

herehere有一些鏈接,可以幫助

+0

如何獲得的MBean我只能看到getDomains()中的MBeanServerConnection類的列表 – sanre6 2012-02-09 06:15:31

+0

我已經更新了我的答案,包括 – 2012-02-09 06:19:02

3

爲獲得使用內存本地/遠程tomcat的代碼片段:

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://{remote ip/localhost}:2020/jmxrmi"); 
     JMXConnector jmxc = JMXConnectorFactory.connect(url); 
     MBeanServerConnection server = jmxc.getMBeanServerConnection(); 
     Object o = jmxc.getMBeanServerConnection().getAttribute(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"); 
     CompositeData cd = (CompositeData) o; 
     System.out.println(cd.get("used"));