如何通过了解进程ID连接到本地服务器JMX?(How to connect to a local J

2019-08-02 09:29发布

这背后的动机是管理本地Java服务,使用JMX,没有更多的东西像Java服务包装重量级。

每个服务都开始-Dcom.sun.management.jmxremote这意味着“JVM是配置为本地(同一台计算机上只),JMX服务器一起工作。” (见这里有一个良好的交代)。

我尝试了附加API ,但反对决定,因为它不与Java SE6和捆绑,并与Maven集成这是不可能的。

Answer 1:

@Tim布泰

如果ConnectorAddressLink.importFrom返回null,尝试加载管理-agent.jar中为VM。

例如具有类似功能startManagementAgent从https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/test/sun/management/jmxremote/bootstrap/TestManager.java

private static void startManagementAgent(String pid) throws IOException {
    /*
     * JAR file normally in ${java.home}/jre/lib but may be in ${java.home}/lib
     * with development/non-images builds
     */
    String home = System.getProperty("java.home");
    String agent = home + File.separator + "jre" + File.separator + "lib"
            + File.separator + "management-agent.jar";
    File f = new File(agent);
    if (!f.exists()) {
        agent = home + File.separator + "lib" + File.separator +
            "management-agent.jar";
        f = new File(agent);
        if (!f.exists()) {
            throw new RuntimeException("management-agent.jar missing");
        }
    }
    agent = f.getCanonicalPath();

    System.out.println("Loading " + agent + " into target VM ...");

    try {
        VirtualMachine.attach(pid).loadAgent(agent);
    } catch (Exception x) {
        throw new IOException(x.getMessage());
    }
}


Answer 2:

我张贴的问题分享解决方案,因为我没有在这里(Q&A)看到它。 这里的关键是使用ConnectorAddressLink.importFrom(pid)来获取地址。

public static MBeanServerConnection getLocalMBeanServerConnectionStatic(int pid) {
    try {
        String address = ConnectorAddressLink.importFrom(pid);
        JMXServiceURL jmxUrl = new JMXServiceURL(address);
        return JMXConnectorFactory.connect(jmxUrl).getMBeanServerConnection();
    } catch (IOException e) {
        throw new RuntimeException("Of course you still have to implement a good connection handling");
    }
}


文章来源: How to connect to a local JMX server by knowing the process id?