问题
Is it possible to get the memory usage statistics of a tomcat server using JMX API. Which Mbean can provide me this info? I am stuck at the formation of ObjectName in the below code
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("-----");
Wonder how jconsole draws the memory graphs, any pointers for the source code?
回答1:
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());
回答2:
code snippet for getting used memory for local/remote 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"));
回答3:
sample code
List memBeans = // get list of mbeans for (Iterator 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;
}
here and here are some links which can help
来源:https://stackoverflow.com/questions/9206002/how-to-get-memory-usage-of-tomcat-7-using-jmx-api