且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过java代码设置JMX远程端口系统环境参数进行远程监控?

更新时间:2023-12-03 14:20:46

kbec的答案显示方式,但对我不起作用 - 但是通过查看这篇文章我能够修改它并获得一个有效的解决方案。

kbec's answer showed the way but did not work for me - however by looking at this post I was able to modify it and get a working solution.

public static String loadJMXAgent(int port) throws IOException,
        AttachNotSupportedException, AgentLoadException,
        AgentInitializationException {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    VirtualMachine vm = VirtualMachine.attach(name.substring(0,
            name.indexOf('@')));

    String lca = vm.getAgentProperties().getProperty(
            "com.sun.management.jmxremote.localConnectorAddress");
    if (lca == null) {
        Path p = Paths.get(System.getProperty("java.home")).normalize();
        if (!"jre".equals(p.getName(p.getNameCount() - 1).toString()
                .toLowerCase())) {
            p = p.resolve("jre");
        }
        File f = p.resolve("lib").resolve("management-agent.jar").toFile();
        if (!f.exists()) {
            throw new IOException("Management agent not found");
        }
        String options = String.format("com.sun.management.jmxremote.port=%d, " +
                "com.sun.management.jmxremote.authenticate=false, " +
                "com.sun.management.jmxremote.ssl=false", port);
        vm.loadAgent(f.getCanonicalPath(), options);
        lca = vm.getAgentProperties().getProperty(
                "com.sun.management.jmxremote.localConnectorAddress");
    }
    vm.detach();
    return lca;
}

这适用于Eclipse但是在命令行中使用它是一个不同的问题 - 这里有一些讨论为什么在Linux上使用Java Attach API会失败? (即使maven构建完成)
但我发现在我的类路径中添加$ JAVA_HOME / lib / tools.jar解决了这个问题。

This works in Eclipse however getting it to work at the command line is a different matter - there is some discussion about this here Why does using the Java Attach API fail on linux? (even though maven build completes) but I found adding $JAVA_HOME/lib/tools.jar to my classpath solved the problem.