首页 > 学院 > 开发设计 > 正文

在一台机器上通过JMX进行跨JVM的本地调用

2019-11-08 02:21:52
字体:
来源:转载
供稿:网友
import java.io.File;import java.io.IOException;import java.util.PRoperties;import javax.management.MBeanServerConnection;import javax.management.remote.JMXConnector;import javax.management.remote.JMXConnectorFactory;import javax.management.remote.JMXServiceURL;import com.sun.tools.attach.AgentInitializationException;import com.sun.tools.attach.AgentLoadException;import com.sun.tools.attach.AttachNotSupportedException;import com.sun.tools.attach.VirtualMachine;/** * * 通过jmx本地连接 */public class JmxLocalConnector { private VirtualMachine virtualmachine; private JMXConnector connector; /** * *pid为连接的进程id */ public MBeanServerConnection connect(String pid) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException { String address = attachJmx(pid); JMXServiceURL serviceURL = new JMXServiceURL(address); connector = JMXConnectorFactory.connect(serviceURL); return connector.getMBeanServerConnection(); } public void disConnect() { if (virtualmachine != null) { try { virtualmachine.detach(); } catch (IOException e) { e.printStackTrace(); } } if (connector != null) { try { connector.close(); } catch (IOException e) { e.printStackTrace(); } } } private String attachJmx(String pid) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException { virtualmachine = VirtualMachine.attach(pid); String javaHome = virtualmachine.getSystemProperties().getProperty("java.home"); String agentPath = javaHome + File.separator + "jre" + File.separator + "lib" + File.separator + "management-agent.jar"; File file = new File(agentPath); if (!file.exists()) { agentPath = javaHome + File.separator + "lib" + File.separator + "management-agent.jar"; file = new File(agentPath); if (!file.exists()) throw new IOException("Management agent not found"); } agentPath = file.getCanonicalPath(); virtualmachine.loadAgent(agentPath, "com.sun.management.jmxremote"); Properties properties = virtualmachine.getAgentProperties(); String address = (String) properties.get("com.sun.management.jmxremote.localConnectorAddress"); virtualmachine.detach(); return address; }}

通过以上方式创建出MBeanServerConnection ,即可通过它对另一个JVM进行JMX调用,并不需要新开端口


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表