JMX操作实例--做一回技术控

简介:

我来做一回技术控,这部分内容也是简单的API调用例子而已,做一回技术控,发点小骚文,不过你看了,也许知道JConsole是怎么做出来的了,呵呵!

先不用管他干什么,代码运行后,自己改改自然知道做什么的。


例子全部应该都可以运行,使用者,拷贝回去就基本可以用了,无需其他内容的支持,有部分代码对JDK的版本有要求,例如在使用:ThreadMXBean.getThreadAllocatedBytes(id),这个是在JDK 6 update 25中开始支持的,而且在JDK 1.6中获取出来还有问题不少


我先写了个简单的工具类:

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Set;
import javax.management.AttributeNotFoundException;
import javax.management.BadAttributeValueExpException;
import javax.management.BadBinaryOpValueExpException;
import javax.management.BadStringOperationException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidApplicationException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.RuntimeMBeanException;

public class JMXUtils {

	private final static MBeanServer DEFAULT_MBEAN_SERVER = ManagementFactory
			.getPlatformMBeanServer();

	public static long getYongGC() {
		return getYoungGC(DEFAULT_MBEAN_SERVER);
	}

	public static long getFullGC() {
		return getFullGC(DEFAULT_MBEAN_SERVER);
	}

	public static long findLoadedClass() {
		return findLoadedClass(DEFAULT_MBEAN_SERVER);
	}

	public static long getYoungGC(MBeanServerConnection mbeanServer) {
		try {
			ObjectName objectName;
			if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ParNew"))) {
				objectName = new ObjectName("java.lang:type=GarbageCollector,name=ParNew");
			} else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=Copy"))) {
				objectName = new ObjectName("java.lang:type=GarbageCollector,name=Copy");
			} else {
				objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS Scavenge");
			}
			return (Long) mbeanServer.getAttribute(objectName , "CollectionCount");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static long getFullGC(MBeanServerConnection mbeanServer) {
		try {
			ObjectName objectName;
			if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"))) {
				objectName = new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep");
			} else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact"))) {
				objectName = new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact");
			} else {
				objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS MarkSweep");
			}
			return (Long) mbeanServer.getAttribute(objectName , "CollectionCount");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static long findLoadedClass(MBeanServerConnection mBeanServer) {
		try {
			return (Long) (mBeanServer.getAttribute(new ObjectName(
					"java.lang:type=ClassLoading"), "TotalLoadedClassCount"));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void traceOneDomain(String doMain,
			MBeanServerConnection mBeanServer)
			throws MalformedObjectNameException, IntrospectionException,
			InstanceNotFoundException, AttributeNotFoundException,
			ReflectionException, MBeanException, IOException {
		
		Set<ObjectInstance> set = mBeanServer.queryMBeans(new ObjectName(doMain + ":*"), new QueryExp() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean apply(ObjectName name)
					throws BadStringOperationException,
					BadBinaryOpValueExpException,
					BadAttributeValueExpException, InvalidApplicationException {
				return true;
			}

			@Override
			public void setMBeanServer(MBeanServer s) {}
		});
		for (ObjectInstance objectInstance : set) {
			System.out.println("\t\t\t" + objectInstance.getObjectName() + "\t"
					+ objectInstance.getClassName());
			traceMebeanInfo(mBeanServer, objectInstance.getObjectName());
		}
	}

	public static void traceMebeanInfo(MBeanServerConnection mBeanServer,
			ObjectName objectName) throws IntrospectionException,
			InstanceNotFoundException, MalformedObjectNameException,
			ReflectionException, AttributeNotFoundException, MBeanException,
			IOException {
		MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objectName);
		MBeanAttributeInfo[] mBeanAttributes = mBeanInfo.getAttributes();

		System.out.println("\t\t\tMBeanInfos : ");
		for (MBeanAttributeInfo mBeanAttribute : mBeanAttributes) {
			try {
				System.out.println("\t\t\t\t\t"
						+ mBeanAttribute.getName()
						+ "\t"
						+ mBeanAttribute.getType()
						+ "\tvalue = >"
						+ mBeanServer.getAttribute(objectName,
								mBeanAttribute.getName()));
			} catch (RuntimeMBeanException e) {
				if (e.getCause() instanceof UnsupportedOperationException) {
					System.out.println("\t\t\t\t\t" + mBeanAttribute.getName()
							+ "\t" + mBeanAttribute.getType()
							+ "\tvalue = > value not supported");
				}
			}

		}
	}

	public static void traceAll(MBeanServerConnection mBeanServer)
			throws MalformedObjectNameException, IntrospectionException,
			InstanceNotFoundException, AttributeNotFoundException,
			ReflectionException, MBeanException, IOException {
		System.out.println("MBean count = " + mBeanServer.getMBeanCount());
		String[] domains = mBeanServer.getDomains();
		for (String domain : domains) {
			System.out.println("\tbegin trace domain -> " + domain);
			traceOneDomain(domain, mBeanServer);
		}
	}
}

这个类写好后,我们就可以写点小测试代码了,呵呵!

那么首先来写个遍历所有的参数列表,层次结构为3层:

MBeanServer -> DoMain -> MBean -> MBeanAttributeInfo 但是写好那个Util后调用就简单了:


import java.io.IOException;
import java.lang.management.ManagementFactory;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.ReflectionException;

public class MBeanServerTest {

	public static void main(String[] args) throws MalformedObjectNameException,
			IntrospectionException, InstanceNotFoundException,
			AttributeNotFoundException, ReflectionException, MBeanException,
			IOException {
		// System.gc();
		// System.out.println(JMXUtils.getYongGC());
		// System.out.println(JMXUtils.getFullGC());

		JMXUtils.traceAll(ManagementFactory.getPlatformMBeanServer());

	}
}

结果很多,不同的OS,不同的JVM配置,结果也会有所区别,大家可以自己书出来看看,这里注意里面的ObjectName,通过MBeanServer直接获取里面的参数值,比较好用,尤其是RMI的时候,这个trace不太好用,因为远程可能有些类,本地没有,但是参数值是可以获取到的,所以需要知道名称是比较好的。

远程的输出,我们简单来写一段代码:

import java.io.IOException;
import java.util.HashMap;

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

public class MBeanServerRemoteTest {

	/**
	 * 远程地址需要开启:
	 * -Dcom.sun.management.jmxremote 
	 * -Dcom.sun.management.jmxremote.port=9000 
	 * -Dcom.sun.management.jmxremote.authenticate=true
	 */
	final static String RMI_URL = "service:jmx:rmi:///jndi/rmi://xxx.xxx.xxx.xxx:9000/jmxrmi";

	public static void main(String []args) 
		throws IOException, MalformedObjectNameException, IntrospectionException, 
			InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException {
		JMXServiceURL serviceURL = new JMXServiceURL(RMI_URL);
		JMXConnector jmxc = JMXConnectorFactory.connect(serviceURL , new HashMap<String , Object>() {
			private static final long serialVersionUID = 1L;
			{
				put(JMXConnector.CREDENTIALS , new String[] {"controlRole" , "FUCK"});
			}
		});
		MBeanServerConnection mBeanServer = jmxc.getMBeanServerConnection();
		System.out.println("MBean count = " + mBeanServer.getMBeanCount());
		String[] domains = mBeanServer.getDomains();
		for (String doMain : domains) {
			System.out.println("============>" + doMain);
		}
		System.out.println(JMXUtils.getYoungGC(mBeanServer));
		System.out.println(JMXUtils.getFullGC(mBeanServer));
		System.out.println(mBeanServer.getAttribute(new ObjectName("JMImplementation:type=MBeanServerDelegate"), "ImplementationVersion"));
		System.out.println(mBeanServer.getAttribute(new ObjectName("java.lang:type=Runtime"), "BootClassPath"));
		//其余的可以自己遍历出来
	}
}

这两个出来了,其实JMX还提供了些简单的,默认的MXBean,可以直接使用,我们简单也写下这些demo,可以拿去自己玩哈。


===》ClassLoadingMXBean

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;

public class ClassLoadingMXBeanTest {

	public static void main(String []args) {
		ClassLoadingMXBean classLoadingMXBean = ManagementFactory.getClassLoadingMXBean();
		System.out.println(classLoadingMXBean.getLoadedClassCount());
		System.out.println(classLoadingMXBean.getTotalLoadedClassCount());
		System.out.println(classLoadingMXBean.getUnloadedClassCount());
		System.out.println(classLoadingMXBean.isVerbose());
	}
}

===》CompilationMXBean

import java.lang.management.CompilationMXBean;
import java.lang.management.ManagementFactory;

public class CompilationMXBeanTest {

	public static void main(String []args) {
		CompilationMXBean mxBean = ManagementFactory.getCompilationMXBean();
		System.out.println(mxBean.getTotalCompilationTime());
		System.out.println(mxBean.getName());
		System.out.println(mxBean.isCompilationTimeMonitoringSupported());
	}
}

===》MemoryManagerMXBean

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryManagerMXBean;
import java.util.List;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.ReflectionException;

public class MemoryManagerMXBeanTest {

	public static void main(String []args) throws IntrospectionException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException {
		MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
		System.gc();
		
		List<MemoryManagerMXBean> list = ManagementFactory.getMemoryManagerMXBeans();
		for(MemoryManagerMXBean memoryManagerMXBean : list) {
			System.out.println(memoryManagerMXBean.getName());
			System.out.println(memoryManagerMXBean.getObjectName());
			MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(memoryManagerMXBean.getObjectName());
			
			MBeanAttributeInfo[] mBeanAttributes = mBeanInfo.getAttributes();
			for(MBeanAttributeInfo mBeanAttribute : mBeanAttributes) {
				System.out.println("=============>" + mBeanAttribute.getName() + "\t" + mBeanAttribute.getType());
				System.out.println("=============value = >" + mBeanServer.getAttribute(memoryManagerMXBean.getObjectName(), mBeanAttribute.getName()));
			}
			
			/*String []poolNames = memoryManagerMXBean.getMemoryPoolNames();
			for(String poolName : poolNames) {
				System.out.println("\t" + poolName);
			}*/
		}
	}
}


===》MemoryMXBean
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;

public class MemoryMXBeanTest {

	public static void main(String []args) {
		MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
		//memoryMXBean.gc();
		System.out.println(memoryMXBean.getHeapMemoryUsage());
		System.out.println(memoryMXBean.getObjectPendingFinalizationCount());
		System.out.println(memoryMXBean.getNonHeapMemoryUsage());
	}
}


===》MemoryPoolMXBean

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.List;

public class MemoryPoolMXBeanTest {

	public static void main(String[] args) {
		List<MemoryPoolMXBean> list = ManagementFactory.getMemoryPoolMXBeans();
		for (MemoryPoolMXBean memoryPoolMXBean : list) {
			System.out.println(memoryPoolMXBean.getName()
					+ memoryPoolMXBean.getCollectionUsage()
					+ "\n\nPeakUsage:\t\t" + memoryPoolMXBean.getPeakUsage()
					+ "\n\nUsage:\t\t" + memoryPoolMXBean.getUsage());
			/*
			 * + memoryPoolMXBean.getUsageThreshold() + "\t" +
			 * memoryPoolMXBean.getUsageThresholdCount() +
			 * "\t\n\nCollectionUsage:\t\t"
			 * 
			 * + memoryPoolMXBean.getType() + "\t"
			 */
			// memoryPoolMXBean.getCollectionUsageThreshold() + "\t"
			// memoryPoolMXBean.getCollectionUsageThresholdCount() + "\t" );
			// String []memoryManagerNames =
			// memoryPoolMXBean.getMemoryManagerNames();
			/*
			 * for(String memoryManagerName : memoryManagerNames) {
			 * System.out.println("\t\t\t\t" + memoryManagerName); }
			 */

		}
	}
}


===》OperatingSystemMXBean

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;

public class OperatingSystemMXBeanTest {

	public static void main(String []args) {
		OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
		System.out.println(mxBean.getArch());
		System.out.println(mxBean.getAvailableProcessors());
		System.out.println(mxBean.getName());
		System.out.println(mxBean.getSystemLoadAverage());
		System.out.println(mxBean.getVersion());
	}
}

===》RuntimeMXBean

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

public class RuntimeMXBeanTest {

	public static void main(String []args) {
		RuntimeMXBean runTimeMXBean = ManagementFactory.getRuntimeMXBean();
		System.out.println(runTimeMXBean.getBootClassPath());
		System.out.println(runTimeMXBean.getClassPath());
		System.out.println(runTimeMXBean.getLibraryPath());
		System.out.println(runTimeMXBean.getManagementSpecVersion());
		System.out.println(runTimeMXBean.getName());
		System.out.println(runTimeMXBean.getSpecName());
		System.out.println(runTimeMXBean.getSpecVendor());
		System.out.println(runTimeMXBean.getStartTime());
		System.out.println(runTimeMXBean.getUptime());
		System.out.println(runTimeMXBean.getVmName());
		System.out.println(runTimeMXBean.getVmVendor());
		System.out.println(runTimeMXBean.getVmVersion());
		System.out.println(runTimeMXBean.getInputArguments());
		System.out.println(runTimeMXBean.getSystemProperties());
	}
}

===》ThreadMXBean

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;

import com.sun.management.ThreadMXBean;
//import sun.management.VMOptionCompositeData;
//import com.sun.management.VMOption;
//import java.lang.management.ManagementFactory;

public class ThreadMXBeanTest {

	public static void main(String []args) {
		ThreadMXBean thredMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
		long []ids = thredMXBean.getAllThreadIds();
		for(long id : ids) {
			System.out.println(id + "\t" + thredMXBean.getThreadAllocatedBytes(id) + "\t" + thredMXBean.getThreadInfo(id));
		}
		System.out.println(thredMXBean.getCurrentThreadCpuTime());
		System.out.println(thredMXBean.getCurrentThreadUserTime());
		System.out.println(thredMXBean.getDaemonThreadCount());
		System.out.println(thredMXBean.getPeakThreadCount());
		System.out.println(thredMXBean.getThreadCount());
		System.out.println(thredMXBean.getTotalStartedThreadCount());
		System.out.println("==========================>");
		displayThreadInfos(thredMXBean , ids);
	}
	
	
	private static void displayThreadInfos(ThreadMXBean thredMXBean , long []ids) {
		ThreadInfo []threadInfos = thredMXBean.getThreadInfo(ids);
		for(ThreadInfo thread : threadInfos) {
			System.out.println(thread.getThreadName() + "\t" 
					+ thread.getLockOwnerId() + "\t" + thread.getThreadState() 
					+ "\t" + thread.getBlockedCount() + "\t" + thread.getBlockedTime() );
			
		}
	}
}






目录
相关文章
|
6月前
|
监控 Serverless 文件存储
函数计算操作报错合集之启动服务时候超时,该如何解决
在使用函数计算服务(如阿里云函数计算)时,用户可能会遇到多种错误场景。以下是一些常见的操作报错及其可能的原因和解决方法,包括但不限于:1. 函数部署失败、2. 函数执行超时、3. 资源不足错误、4. 权限与访问错误、5. 依赖问题、6. 网络配置错误、7. 触发器配置错误、8. 日志与监控问题。
|
7月前
|
Java
Springboot项目启动失败: (JVM running for 2.723) 与目标 VM 断开连接, 地址为: ‘‘127.0.0.1:23604‘,传输: ‘套接字‘‘
Springboot项目启动失败: (JVM running for 2.723) 与目标 VM 断开连接, 地址为: ‘‘127.0.0.1:23604‘,传输: ‘套接字‘‘
400 0
|
应用服务中间件
【端口号清除工具】port is already in use解决利器,从此告别每次输入命令杀端口
【端口号清除工具】port is already in use解决利器,从此告别每次输入命令杀端口
161 0
|
消息中间件 Kafka Shell
Kafka的保姆级简易安装启动、关闭注意事项、简单使用
Kafka的保姆级简易安装启动、关闭注意事项、简单使用
1461 0
OushuDB 基本用法 启动/停止
OushuDB 基本用法 启动/停止
71 0
震精!Dozer 宣布停止维护,不要再用了
旨在优雅的代替满屏的 get/set 以及 BeanUtils 工具类,然后栈长也收到了一些留言,其中很多朋友就是推荐使用 Dozer 答:
|
JSON NoSQL Go
GoFrame gredis 硬核解析 | DoVar、Conn连接对象、自动序列化
详细的介绍了gredis的使用,包括:Do/DoVar方法的使用及区别、复杂场景下使用Conn方法从连接池中获取一个redis连接对象、当给定的参数为map, slice, struct时,gredis内部支持自动对其使用json序列化,并且读取数据时可使用gvar.Var的转换功能实现反序列化。
232 0
GoFrame gredis 硬核解析 | DoVar、Conn连接对象、自动序列化
|
JSON 监控 Java
zabbix精华篇-低级自动发现详解---批量自动获取主机所有tomcat端口并进行监控(二十四)
zabbix利用低级自动发现自动监控tomcat端口 1.为什么要使用自动发现 由于我们tomcat服务器特别多,且每一个上面跑的实例长达几十个,但是这些tomcat的端口也都需要监控起来,如果手动添加的话将会非常麻烦,我们可以利用自动发现,将自动发现配置一些规则并做成模板,给有tomcat的服务器链接模板就可以了,这个过程就会大大减少人工的工作量
528 0
zabbix精华篇-低级自动发现详解---批量自动获取主机所有tomcat端口并进行监控(二十四)
|
监控 网络协议 关系型数据库
zabbix自动化监控---自动注册机制(二十三)
zabbix自动监控之自动注册 1.自动注册介绍 zabbix自动发现的效率非常慢,每次自动发现的时候都需要对所有的主机进行扫描,也类似与zabbix被动模式,每次都需要向机器进行一次探测,比如这次某个主机没有存在,下次上线了又要重新扫描一次,效率非常低下。 而zabbix自动注册的原理就类似主动模式,每次都是由zabbix-agent主动去向zabbix-server说我上线了,需要加入监控,这时zabbix-server同意后立马就加入监控了,这个效率是非常高的 zabbix自动注册只需要配置四个地方即可生效
417 0
zabbix自动化监控---自动注册机制(二十三)
|
监控 Linux
zabbix自动化监控---自动发现机制(二十二)
zabbix自动监控之自动发现 1.自动发现介绍 当我们有上千台主机都需要加监控的时候用自动发现会非常方便,只需要我们创建一个自动发现规则,设置自动发现的范围,在根据设置的动作就可以将已经安装好agent的Linux服务器自动的添加到监控上
946 0
zabbix自动化监控---自动发现机制(二十二)