package com.jvm;

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.ThreadMXBean;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class Main {

	public static void main(String[] args) {
		if(args.length==0){
			System.out.println("please input jmx port!");
			System.exit(0);
		}			
		Main main = new Main();
		String port = args[0];
		try {
			JMXServiceURL address = new JMXServiceURL(
					"service:jmx:rmi:///jndi/rmi://172.16.13.111:" + port
							+ "/jmxrmi");
			JMXConnector connector = JMXConnectorFactory.connect(address);
			MBeanServerConnection mbs = connector.getMBeanServerConnection();
			String result = main.getClasses(mbs)+":"+main.getMemory(mbs)+":"+main.getThread(mbs);
			System.out.println(result);
			connector.close();
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	public String getClasses(MBeanServerConnection mbs) throws IOException {
		ClassLoadingMXBean cbean = ManagementFactory.newPlatformMXBeanProxy(
				mbs, ManagementFactory.CLASS_LOADING_MXBEAN_NAME,
				ClassLoadingMXBean.class);
		return("ClassLoadingMXBean:" +
				"getLoadedClassCount:"+cbean.getLoadedClassCount() + ":" +
				"getUnloadedClassCount:"+ cbean.getUnloadedClassCount());

	}

	public String getMemory(MBeanServerConnection mbs) throws IOException {
		MemoryMXBean memory = ManagementFactory.newPlatformMXBeanProxy(mbs,
				ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
		MemoryUsage usage = memory.getHeapMemoryUsage();
		MemoryUsage nonUsage = memory.getNonHeapMemoryUsage();
		return("MemoryUsage:" +
				"getInit:"+usage.getInit() + ":" +
				"getMax:" + usage.getMax() + ":" +
				"getUsed:"+ usage.getUsed())+
				(":MemoryNonUsage:" +
				"getInit:"+nonUsage.getInit() + ":" +
				"getMax:" + nonUsage.getMax() + ":" +
			    "getUsed:"+ nonUsage.getUsed());

	}

	public String getThread(MBeanServerConnection mbs) throws IOException {
		ThreadMXBean threadBean = ManagementFactory.newPlatformMXBeanProxy(mbs,
				ManagementFactory.THREAD_MXBEAN_NAME, ThreadMXBean.class);
		 
		return("ThreadMXBean:" +
				"getDaemonThreadCount:"+threadBean.getDaemonThreadCount() + ":" +
				"getPeakThreadCount:"+ threadBean.getPeakThreadCount() + ":" +
				"getTotalStartedThreadCount:"+ threadBean.getTotalStartedThreadCount());

	}

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注