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

后端 未结 6 1237
长发绾君心
长发绾君心 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 13:56

    If you don't specify any jmxremote env as run param then JMX management agent was not loaded. You can try this for dynamic loading :

    public static String loadJMXAgent(int port) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
        System.setProperty("com.sun.management.jmxremote.port", Integer.toString(port));
        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");
    
            vm.loadAgent(f.getCanonicalPath(), "com.sun.management.jmxremote");
            lca = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
        }
        vm.detach();
        return lca;
    }
    

    You must include jdk/lib/tools.jar

提交回复
热议问题