【问题标题】:Access JMX from inside JVM从 JVM 内部访问 JMX
【发布时间】:2012-12-22 03:56:42
【问题描述】:

是否可以从 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 状态,特别是内存使用情况,在将工作数据缓存到磁盘和将其保存在内存中之间切换。设置 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 帖子,因此欢迎任何关于改进等问题的提示。

【问题讨论】:

    标签: java jvm jmx


    【解决方案1】:

    您可以使用此代码轻松获取平台 MBean Server。

    ManagementFactory.getPlatformMBeanServer();
    

    有很多有用的 MBean 可用于收集有关 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";
    }
    

    【讨论】:

    • 谢谢,正是我想要的。大多数教程似乎都侧重于连接远程监控工具。
    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 2015-09-24
    • 2012-02-02
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多