How to set JMX remote port system environment parameters through java code for remote monitoring?

后端 未结 6 1236
长发绾君心
长发绾君心 2020-12-29 13:33

I have a program which requires dynamically (i.e. at run time) opening an available socket and start a JMX agent on it. This JMX parameters are being set inside the Java cod

6条回答
  •  滥情空心
    2020-12-29 14:15

    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;
    }
    

    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.

提交回复
热议问题