/**
* 被监控的服务器添加虚拟机参数
* -Dcom.sun.management.jmxremote.port=9001
* -Dcom.sun.management.jmxremote.ssl=false
* -Dcom.sun.management.jmxremote.authenticate=false
*/
public class MbeanManager {
public static void main(String[] args) throws MalformedObjectNameException, IOException, IntrospectionException, InstanceNotFoundException, ReflectionException {
// JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://192.168.31.236:9001/jmxrmi");
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9001/jmxrmi");
JMXConnector jmx = JMXConnectorFactory.connect(url,null);
MBeanServerConnection serverConnection = jmx.getMBeanServerConnection();
//获取GC信息
List<GarbageCollectorMXBean> garbageCollectorMXBeanList = ManagementFactory.getPlatformMXBeans(serverConnection, GarbageCollectorMXBean.class);
garbageCollectorMXBeanList.stream().forEach(garbageCollectorMXBean -> {
System.out.println(garbageCollectorMXBean.getName()); //GC 名称
System.out.println(garbageCollectorMXBean.getCollectionTime()); //GC 总耗时
System.out.println(garbageCollectorMXBean.getCollectionCount()); //GC 次数
Optional.ofNullable(garbageCollectorMXBean.getLastGcInfo()).ifPresent(gcInfo -> {
System.out.println(gcInfo.getMemoryUsageAfterGc());// GC之后的内存使用率
});
});
//获取内存信息
MemoryMXBean memoryMXBean = ManagementFactory.getPlatformMXBean(serverConnection, MemoryMXBean.class);
System.out.println(memoryMXBean.getHeapMemoryUsage());//内存使用率
System.out.println(memoryMXBean.getNonHeapMemoryUsage());//堆外内存使用率
//获取操作系统信息
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getPlatformMXBean(serverConnection, OperatingSystemMXBean.class);
System.out.println(operatingSystemMXBean.getSystemCpuLoad());//系统负载
System.out.println(operatingSystemMXBean.getProcessCpuLoad());//进程负载
System.out.println(operatingSystemMXBean.getFreePhysicalMemorySize());//空闲物理内存
System.out.println(operatingSystemMXBean.getTotalPhysicalMemorySize());//物理内存
System.out.println(operatingSystemMXBean.getCommittedVirtualMemorySize());//可用于当前虚拟机的虚拟内存
System.out.println(operatingSystemMXBean.getFreeSwapSpaceSize());// 空闲的交换区
System.out.println(operatingSystemMXBean.getVersion());//操作系统版本
System.out.println(operatingSystemMXBean.getProcessCpuTime());//进程获取的CPU时间
//获取线程信息
ThreadMXBean threadMXBean = ManagementFactory.getPlatformMXBean(serverConnection, ThreadMXBean.class);
System.out.println(threadMXBean.getPeakThreadCount());//峰值线程数
System.out.println(threadMXBean.getThreadCount());//当前线程数
System.out.println(threadMXBean.getDaemonThreadCount());//启动的守护线程总数
System.out.println(threadMXBean.getTotalStartedThreadCount());//启动的线程总数
}
}