![](/img/trans.png)
[英]How to connect to JMX for JVM on local machine by pid (Java 9+)
[英]How to connect to a local JMX server by knowing the process id?
其背后的動機是使用JMX管理本地Java服務,而沒有像Java服務Wrapper這樣的重量級東西。
每個服務均以-Dcom.sun.management.jmxremote
開始,這意味着“ JVM已配置為充當本地(僅同一台機器)JMX服務器。” (有關詳細說明,請參見此處 )。
我嘗試了Attach API ,但由於它未與Java SE6捆綁在一起並且無法與maven集成,因此決定拒絕它。
我發布問題以共享解決方案,因為我在這里沒有看到它(問與答)。 此處的關鍵是使用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");
}
}
@蒂姆·布特
如果ConnectorAddressLink.importFrom
返回null,請嘗試將management-agent.jar加載到VM。
例如,使用https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/test/sun/management/jmxremote/bootstrap/TestManager.java中的功能startManagementAgent
類的東西
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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.