我来做一回技术控,这部分内容也是简单的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() ); }
}
}

JMX操作实例--做一回技术控的更多相关文章

  1. oracle 单实例DG(闪回技术四)

    一,flashback Oracle Flashback技术是一组数据库特性,它可以让你查看数据库对象的过去状态,或者将数据库对象返回到以前的状态,而无需使用基于时间点的介质恢复.根据数据库的变化,闪 ...

  2. Oracle的闪回技术--闪回错误的DML操作

    提交DML操作后,该操作使用的还原段就可以被其它对象使用了,为了保证闪回操作时这些数据仍然被保存在还原段中,可能需要重新设置undo_retention参数,表示一个事务提交后,该事务的数据必须保存在 ...

  3. Oracle 六闪回技术,flashback

    Flashback 技术基于Undo segment基于内容的, 因此,限制UNDO_RETENTON参数. 要使用flashback 特征,您必须启用自己主动撤销管理表空间. 在Oracle 11g ...

  4. (4.11)mysql备份还原——mysql闪回技术(基于binlog)

    0.闪回技术与工具简介 mysql闪回工具比较流行三大类: [0.1]官方的mysqlbinlog:支持数据库在线/离线,用脚本处理binlog的输出,转化成对应SQL再执行.通用性不好,对正则.se ...

  5. OCP读书笔记(10) - 使用闪回技术I

    使用闪回技术查询数据 闪回查询:就是查询表在过去某个时间点的数据,所用到的技术就是undo数据 SQL> conn scott/tiger 创建测试表 SQL> create table ...

  6. Oracle闪回技术

    (一)闪回技术概要 闪回技术是数据库备份与恢复的重要补充手段,主要包括以下7种特性: 特性 原理 数据库支持 闪回查询(Flashback Query) 利用undo表空间中的回退信息,查询过去某个时 ...

  7. oracle-闪回技术1

    http://blog.csdn.net/lqx0405/article/details/44776737  Oracle Study案例之--基于表空间的时间点恢复(TSPITR) DBPITR 数 ...

  8. SQL Fundamentals: 表的创建和管理(表的基本操作,闪回技术flashback,表结构修改)

    SQL Fundamentals || Oracle SQL语言 1.表的基本操作 (CREATE TABLE, DROP TABLE,TRUNCATE TABLE, RENAME tablename ...

  9. Oracle 的闪回技术 --flashback

    SQL Fundamentals: 表的创建和管理 如何开启数据库闪回? SQL> shutdown immediate; ORA-01109: database not open Databa ...

随机推荐

  1. Mutex, semaphore, spinlock的深度解析

    Mutex是一把钥匙,一个人拿了就可进入一个房间,出来的时候把钥匙交给队列的第一个.一般的用法是用于串行化对critical section代码的访问,保证这段代码不会被并行的运行. Semaphor ...

  2. grep 中的正则表达式【转】

    正则表达式 正则表达式就是用于匹配每行输入的一种模式,模式是指一串字符序列.下面是范例: ^w1 w1|w2 [^ ] grep 正则表达式示例 在 /etc/passswd 目录中搜索 'vivek ...

  3. 数据结构与算法之KMP 字符串匹配

    举例来说,有一个字符串"DSFFKFJD KFJLKFDLJFJ IWWJKJFJIA",我想知道,里面是否包含另一个字符串"JFJI",有的话就返回在原字符串 ...

  4. 虚拟机NAT网络设置

    1. 虚拟机设置 2. 本地网络设置 3. 本地虚拟网卡设置 4. 安装虚拟机,设置网络为NAT方式即可访问外网.

  5. jfinal文件上传

    jfianl获取表单数据,需要先getFile()获取文件,再使用getPara() public class ImageUploadController extends Controller{ pu ...

  6. Appium+python 一个简单的登录测试实例

    # coding=utf-8 from appium import webdriver import time import unittest import os import HTMLTestRun ...

  7. 用WP SMTP插件实现邮件发送功能

    WordPress本身是采用mail()函数发邮件的,但是这样发出的邮件很容易被放入垃圾箱,很多主机商(特别是Windows主机)为了避免用户滥发邮件直接禁用了mail()函数,还有些云计算平台(比如 ...

  8. Expert C Programming 阅读笔记(CH2)

    P33    Bugs are by far the largest and most successful class of entity, with nearly a million known ...

  9. day4 二维数组旋转90度

    二维数组的旋转其实就是数组里面的元素对调的情况:下面有一个4×4的二维数组,[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]],现在要求把 ...

  10. SCU 4445 Right turn

    模拟. 每次找一下即将要遇到的那个点,这个数据范围可以暴力找,自己的写的时候二分了一下.如果步数大于$4*n$一定是$-1$. #include<bits/stdc++.h> using ...