在JVM内部访问JMX

7

在JVM实例内部是否可以访问JVM的JMX服务器?还是必须通过标准的套接字/端口远程接口进行连接?

+----------------------------------------+   Option 2: Connect
|       +---------------------------+    |   through sockets like
|       | My Notification Listener  |+----->----------+ a remote
|       |                           |    |            | monitor.
|       +---------------------------+    |            |
|                           +            |            |
|          Option 1: connect|            |            |
|          to the internal  |            |            |
|          JMX server. I'm  |            |            |
|          trying to find   |            |            |
|          if this is possible.          |            |
|                           |            |            |
|                           |            |            |
|    A single JVM instance. |            |            |
|                           |            |            |
|        +------------+-----v------+--+  |            |
|        |            | GuageMXBean|<-+<--------------+
|        |            +------------+  |  |
|        | JMX MXBean Server          |  |
|        +----------------------------+  |
+----------------------------------------+

背景:我正在尝试实现一个“智能”系统,它可以响应JVM状态,特别是内存使用情况,可以在缓存工作数据和将其保存在RAM中之间进行切换。设置JMX监听器似乎比运行后台线程更加优雅,做类似以下事情的操作:

Runtime RTime = Runtime.getRuntime();
while(!shutdown)
{
    if((RTime.totalMemory / RTime.maxMemory) > upperThreshold) cachmode = CACHETODISK;
    if((RTime.totalMemory / RTime.maxMemory) < lowerThreshold) cachmode = CACHETORAM;
    Sleep(1000);
}

桌面应用程序,如果有区别的话。

这是我第一次在SO上发帖,所以欢迎任何改进问题等方面的提示。

1个回答

8
您可以使用以下代码轻松获取平台MBean服务器。
ManagementFactory.getPlatformMBeanServer();

有很多有用的MBeans可用于收集有关JVM状态的信息,这里是一个简单的示例

List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); 

// generate heap state report 
String report = "";     
for (GarbageCollectorMXBean gc : gcBeans) {
    report += "\nGC Name         : " + gc.getName();
    report += "\nCollection count: " + gc.getCollectionCount();
    report += "\nCollection Time : " + gc.getCollectionTime() + " milli seconds";
    report += "\n";
}       

List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean pool : memoryPoolMXBeans) {
    report += "\nMemory Pool: " + pool.getName();
    MemoryUsage usage = pool.getUsage();
    report += "\n   Max : " + usage.getMax() / 1024000 + "MB"; 
    report += "\n   Used: " + usage.getUsed() / 1024000 + "MB";
    report += "\n";
}

谢谢,这正是我想要的。大多数教程似乎都专注于连接远程监控工具。 - SailsMan63

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接