最近做多个远程服务器的系统监控,花费了不少的时间,下面就做一个总结
从JAVA 5开始,JDK提供了一些JVM检测的API,这就是有名的java.lang.management 包,包里提供了许多MXBean的接口类,可以很方便的获取到JVM的内存、GC、线程、锁、class、甚至操作系统层面的各种信息,本文就简单的介绍一种利用JMX对JAVA进程进行CPU、堆内存使用的监控。可能有人会觉得没必要这样做,因为用jconsole之类的工具都能做到,而且会比本文的例子更详细。但是有些时候将console不一定能监控到作为系统服务的java进程,我最近就不得不自己编码去获取远程java进程的监控数据。希望能起到抛砖引玉的作用吧。
第一步:向被监控的服务器Tomcat中添加一段配置代码
详情:http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html#Enabling_JMX_Remote
打开Tomcat的bin文件夹下的catalina.bat文件(用文件编辑软件打开)
添加如下代码:
set CATALINA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8787 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false
在CMD中输入 : jconsole
在远程哪儿输入:
service:jmx:rmi:///jndi/rmi://192.168.85.54:8787/jmxrmi (替换服务器tomcat所在的ip)
可以显示如下图:包括CPU占用率,堆信息,非堆信息,类加载,内存使用情况等,如下图
点开右边的MBean,我们可以获取其对应MBean的ObjectName,然后通过属性和做操的Key值获取想要的数据,如下图
3 实现代码如下:
package pyc.jvm.monitor;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
/**
* 创建时间:2014-11-5 上午11:37:22
*
* @author zhangtianyou
* @version 2.2
*/
public class JMXTest {
//具体格式查看相关的API
private final static String SERVICE_1 = "service:jmx:rmi:///jndi/rmi://192.168.85.54:8787/jmxrmi";
public static void main(String[] args) throws IOException,
MalformedObjectNameException, NullPointerException {
Timer timer = new Timer();
timer.schedule(new JMXTest().new MonitorTask(SERVICE_1), 0, 10000);
}
private class MonitorTask extends TimerTask{
private String service ;
public MonitorTask(String service){
this.service = service;
}
@Override
public void run() {
JMXmonitor(service);
}
}
private static void JMXmonitor(String service) {
JMXConnector connector = null;
try {
JMXServiceURL url = new JMXServiceURL(SERVICE_1);
System.out.println("url: " + SERVICE_1);
connector = JMXConnectorFactory.connect(url);
MBeanServerConnection connection = connector.getMBeanServerConnection();
System.out.println("Catalina:");
ObjectName objectName = new ObjectName("Catalina:type=Engine");
System.out.println("defaultHost:"
+ (String) connection.getAttribute(objectName,
"defaultHost"));
System.out.println("name:" + (String) connection.getAttribute(objectName, "name"));
System.out.println("baseDir:" + (String) connection.getAttribute(objectName,"baseDir"));
connection.getAttribute(objectName, "valveObjectNames");
objectName = new ObjectName("Catalina:type=Host,host=localhost");
javax.management.ObjectName[] a = (javax.management.ObjectName[]) connection
.getAttribute(objectName, "children");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i].toString());
}
System.out.println("\nMemory");
System.out.println("memory: HeapMemoryUsage");
objectName = new ObjectName("java.lang:type=Memory");
CompositeDataSupport heapMemoryUsage = (CompositeDataSupport) connection.getAttribute(objectName, "HeapMemoryUsage");
System.out.println("committed = " + convertKB(heapMemoryUsage.get("committed")));
System.out.println("init = " + convertKB(heapMemoryUsage.get("init")));
System.out.println("max = " + convertKB(heapMemoryUsage.get("max")));
System.out.println("used = " + convertKB(heapMemoryUsage.get("used")));
System.out.println("\nmemory: NonHeapMemoryUsage");
CompositeDataSupport nonHeapMemoryUsage = (CompositeDataSupport) connection.getAttribute(objectName, "NonHeapMemoryUsage");
System.out.println("committed = " + convertKB(nonHeapMemoryUsage.get("committed")));
System.out.println("init = " + convertKB(nonHeapMemoryUsage.get("init")));
System.out.println("max = " + convertKB(nonHeapMemoryUsage.get("max")));
System.out.println("used = " + convertKB(nonHeapMemoryUsage.get("used")));
System.out.println("\nThread");
objectName = new ObjectName("java.lang:type=Threading");
//线程总数
System.out.println("ThreadCount = " + connection.getAttribute(objectName, "ThreadCount"));
//守护线程
System.out.println("DaemonThreadCount = " + connection.getAttribute(objectName, "DaemonThreadCount"));
//返回自从Java虚拟机启动或峰值重置以来峰值活动线程计数
System.out.println("PeakThreadCount = " + connection.getAttribute(objectName, "PeakThreadCount"));
System.out.println("CurrentThreadCpuTime = " + connection.getAttribute(objectName, "CurrentThreadCpuTime") + "ms");
System.out.println("CurrentThreadUserTime = " + connection.getAttribute(objectName, "CurrentThreadUserTime") + "ms");
System.out.println("\nClassLoading");
objectName = new ObjectName("java.lang:type=ClassLoading");
System.out.println("TotalLoadedClassCount = " + connection.getAttribute(objectName, "TotalLoadedClassCount") + "个");
System.out.println("\nCpu");
objectName = new ObjectName("java.lang:type=OperatingSystem");
long start = System.currentTimeMillis();
long startC = (long) connection.getAttribute(objectName, "ProcessCpuTime");
try {
TimeUnit.SECONDS.sleep(5);
} catch (Exception e) {
System.out.println("中断异常");
}
long end = System.currentTimeMillis();
long endC = (long) connection.getAttribute(objectName, "ProcessCpuTime");
//end - start 即为当前采集的时间单元,单位ms
//endT - startT 为当前时间单元内cpu使用的时间,单位为ns
//所以:
int availableProcessors = (int)connection.getAttribute(objectName, "AvailableProcessors");
double ratio = (endC-startC) / 1000000.0 / (end-start) / availableProcessors;
System.out.println("cup使用率 = " + ratio * 100 + "%");
} catch (Exception ex) {
System.out.println(ex);
} finally {
try {
connector.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
private static String convertKB(Object obj){
long src = (long)obj;
if (src <= 0L) {
return "0KB";
}
return (double)src / 1024 + "KB";
}
}
url: service:jmx:rmi:///jndi/rmi://192.168.85.54:8787/jmxrmi
Catalina:
defaultHost:localhost
name:Catalina
baseDir:E:\jmxserver\apache-tomcat1
Catalina:j2eeType=WebModule,name=//localhost/ServletDemo,J2EEApplication=none,J2EEServer=none
Catalina:j2eeType=WebModule,name=//localhost/,J2EEApplication=none,J2EEServer=none
Catalina:j2eeType=WebModule,name=//localhost/manager,J2EEApplication=none,J2EEServer=none
Catalina:j2eeType=WebModule,name=//localhost/docs,J2EEApplication=none,J2EEServer=none
Catalina:j2eeType=WebModule,name=//localhost/examples,J2EEApplication=none,J2EEServer=none
Catalina:j2eeType=WebModule,name=//localhost/host-manager,J2EEApplication=none,J2EEServer=none
Memory
memory: HeapMemoryUsage
committed = 59392.0KB
init = 63667.75KB
max = 906752.0KB
used = 7679.4609375KB
memory: NonHeapMemoryUsage
committed = 31680.0KB
init = 24000.0KB
max = 133120.0KB
used = 17649.6484375KB
Thread
ThreadCount = 53
DaemonThreadCount = 52
PeakThreadCount = 56
CurrentThreadCpuTime = 15600100ms
CurrentThreadUserTime = 15600100ms
ClassLoading
TotalLoadedClassCount = 2581个
Cpu
cup使用率 = 0.07795372776334199%
见下文。