首页 > 代码库 > JMX实现远程服务器系统监控之二

JMX实现远程服务器系统监控之二

接上一篇的下面提供另一种实现方式:

先看一个类图:

JDK实现了九个自带的MBean,这些MBean能够监视虚拟机的所有信息:分别是如下

 


ManagementFactory工厂类通过ObjectName可以获取对应的MBean实例,自然就可以获取想要的数据了


2 代码如下:

package pyc.jvm.monitor;

import java.io.IOException;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.net.MalformedURLException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

/**
 * 创建时间:2014-11-7 上午11:06:34
 * 
 * @author zhangtianyou
 * @version 2.2
 */

public class JMXTest2 {

	private final static String SERVICE_1 = "service:jmx:rmi:///jndi/rmi://192.168.85.54:8787/jmxrmi";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		//10秒调用一次
		Timer timer = new Timer();
		timer.schedule(new JMXTest2(). 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 jmxConnector = null;
		try {
			JMXServiceURL ServiceURL = new JMXServiceURL(service);
			jmxConnector = JMXConnectorFactory.connect(ServiceURL);
			// MBean 服务器(无论是本地的还是远程的)进行通信的一种方式 MBeanServerConnection
			MBeanServerConnection mBeanServerConnection = jmxConnector
					.getMBeanServerConnection();

			// 获取MemoryMXBean
			System.out.println("\nMemory");
			MemoryMXBean memoryMXBean = ManagementFactory
					.newPlatformMXBeanProxy(mBeanServerConnection,
							ManagementFactory.MEMORY_MXBEAN_NAME,
							MemoryMXBean.class);

			MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
			System.out.println("heapMemoryUsage :");
			System.out.println("committed = "
					+ convertKB(heapMemoryUsage.getCommitted()));
			System.out
					.println("init = " + convertKB(heapMemoryUsage.getInit()));
			System.out.println("max = " + convertKB(heapMemoryUsage.getMax()));
			System.out
					.println("used = " + convertKB(heapMemoryUsage.getUsed()));

			MemoryUsage nonHeapMemoryUsage = memoryMXBean
					.getNonHeapMemoryUsage();
			System.out.println("\nnonHeapMemoryUsage :");
			System.out.println("committed = "
					+ convertKB(nonHeapMemoryUsage.getCommitted()));
			System.out.println("init = "
					+ convertKB(nonHeapMemoryUsage.getInit()));
			System.out.println("max = "
					+ convertKB(nonHeapMemoryUsage.getMax()));
			System.out.println("used = "
					+ convertKB(nonHeapMemoryUsage.getUsed()));

			// 获取 ThreadMXBean
			System.out.println("\nThread");
			ThreadMXBean threadMXBean = ManagementFactory
					.newPlatformMXBeanProxy(mBeanServerConnection,
							ManagementFactory.THREAD_MXBEAN_NAME,
							ThreadMXBean.class);
			System.out
					.println("ThreadCount = " + threadMXBean.getThreadCount());
			System.out.println("DaemonThreadCount = "
					+ threadMXBean.getDaemonThreadCount());
			System.out.println("PeakThreadCount = "
					+ threadMXBean.getPeakThreadCount());
			System.out.println("CurrentThreadCpuTime = "
					+ threadMXBean.getCurrentThreadCpuTime());
			System.out.println("CurrentThreadUserTime = "
					+ threadMXBean.getCurrentThreadUserTime());

			System.out.println("\nClassLoading");
			ClassLoadingMXBean classLoadingMXBean = ManagementFactory
					.newPlatformMXBeanProxy(mBeanServerConnection,
							ManagementFactory.CLASS_LOADING_MXBEAN_NAME,
							ClassLoadingMXBean.class);
			// 当前加载到Java虚拟机中类的数量
			System.out.println("LoadedClassCount = "
					+ classLoadingMXBean.getLoadedClassCount());
			// Java 虚拟机开始执行到目前已经加载的类的总数。
			System.out.println("TotalLoadedClassCount = "
					+ classLoadingMXBean.getTotalLoadedClassCount());
			// Java 虚拟机开始执行到目前已经卸载的类的总数。
			System.out.println("UnloadedClassCount = "
					+ classLoadingMXBean.getUnloadedClassCount());

			System.out.println("\nCpu");
			OperatingSystemMXBean operatingSystemMXBean = ManagementFactory
					.newPlatformMXBeanProxy(mBeanServerConnection,
							ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME,
							OperatingSystemMXBean.class);
			System.out.println("AvailableProcessors = "
					+ operatingSystemMXBean.getAvailableProcessors());
			double ratio = 0.0;
			long start = System.currentTimeMillis();
			long startC;
			try {
				startC = (long) mBeanServerConnection.getAttribute(operatingSystemMXBean.getObjectName(), "ProcessCpuTime");
				try {
					TimeUnit.SECONDS.sleep(5);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				long end = System.currentTimeMillis();
				long endC = (long) mBeanServerConnection.getAttribute(operatingSystemMXBean.getObjectName(), "ProcessCpuTime");
				
				int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
				ratio = (endC-startC) / 1000000.0 / (end-start) / availableProcessors; 
				
			} catch (AttributeNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (InstanceNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (MBeanException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (ReflectionException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			System.out.println("CUP使用率" + ratio * 100 + "%");
			

		} catch (MalformedURLException e) {
			e.printStackTrace();
			System.out.println("非法的ServiceURL");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (jmxConnector != null) {
					jmxConnector.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private static String convertKB(long src) {

		if (src <= 0L) {
			return "0KB";
		}
		return (double) src / 1024 + "KB";
	}

}


3 运行效果如下:

Memory
heapMemoryUsage :
committed = 59392.0KB
init = 63667.75KB
max = 906752.0KB
used = 21645.8046875KB

nonHeapMemoryUsage :
committed = 30144.0KB
init = 24000.0KB
max = 133120.0KB
used = 17608.9921875KB

Thread
ThreadCount = 53
DaemonThreadCount = 52
PeakThreadCount = 56
CurrentThreadCpuTime = 0
CurrentThreadUserTime = 0

ClassLoading
LoadedClassCount = 2526
TotalLoadedClassCount = 2581
UnloadedClassCount = 55

Cpu
AvailableProcessors = 4
CUP使用率0.07790701158609668%

符合jconsole曲线数据,这种方式更通用,避免了硬编码

JMX实现远程服务器系统监控之二