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() );
			
		}
	}
}






目录
相关文章
|
4月前
|
Kubernetes 监控 Shell
在K8S中,我们公司用户反应pod连接数非常多,希望看一下这些连接都是什么信息?什么状态?怎么排查?容器里面没有集成bash环境、网络工具,怎么处理?
在K8S中,我们公司用户反应pod连接数非常多,希望看一下这些连接都是什么信息?什么状态?怎么排查?容器里面没有集成bash环境、网络工具,怎么处理?
|
7月前
|
Kubernetes 关系型数据库 MySQL
实时计算 Flink版操作报错之将taskmanager.host改为localhost后能够正常运行,但是出现了localhost点灯的问题,是什么导致的
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
|
7月前
|
Arthas 缓存 Java
通过arthas vmtool 调用线上正在运行的service方法
通过arthas vmtool 调用线上正在运行的service方法
253 0
通过arthas vmtool 调用线上正在运行的service方法
|
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‘,传输: ‘套接字‘‘
392 0
quartz(二)动态增删改查停止启用job
quartz(二)动态增删改查停止启用job
64 0
|
消息中间件 Kafka Shell
Kafka的保姆级简易安装启动、关闭注意事项、简单使用
Kafka的保姆级简易安装启动、关闭注意事项、简单使用
1447 0
|
消息中间件 存储 网络协议
抽一根烟的时间学会.NET Core 操作RabbitMQ
抽一根烟的时间学会.NET Core 操作RabbitMQ
188 0
|
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自动注册只需要配置四个地方即可生效
414 0
zabbix自动化监控---自动注册机制(二十三)
|
监控 Linux
zabbix自动化监控---自动发现机制(二十二)
zabbix自动监控之自动发现 1.自动发现介绍 当我们有上千台主机都需要加监控的时候用自动发现会非常方便,只需要我们创建一个自动发现规则,设置自动发现的范围,在根据设置的动作就可以将已经安装好agent的Linux服务器自动的添加到监控上
944 0
zabbix自动化监控---自动发现机制(二十二)