我正在开发一个监控应用程序,它使用 Sigar 进行监控以监控不同类型的应用程序。Sigar 的一个问题是,在监视 Java 应用程序 (JVM) 的堆使用情况时,我只能得到最大堆大小,而不是 JVM 实际使用的堆大小。因此,我扩展了我的监控应用程序以使用 JMX 连接到 JVM 并检索 CPU 以及堆使用情况。到目前为止这工作正常,但我想尽可能地自动化一切,我不想启动我的所有应用程序,被监控,激活 JMX,而是在需要时使用以下代码动态激活它:
private void connectToJVM(final String pid) throws IOException, AgentLoadException, AgentInitializationException {
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor desc : vms) {
if (!desc.id().equals(pid)) {
continue;
}
VirtualMachine vm;
try {
vm = VirtualMachine.attach(desc);
} catch (AttachNotSupportedException e) {
continue;
}
Properties props = vm.getAgentProperties();
String connectorAddress = props.getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib"
+ File.separator + "management-agent.jar";
vm.loadAgent(agent);
// agent is started, get the connector address
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
}
vm.detach();
JMXServiceURL url = new JMXServiceURL(connectorAddress);
this.jmxConnector = JMXConnectorFactory.connect(url);
}
}
到目前为止这工作正常,但问题是我现在依赖于tools.jar
JDK。我现在的问题是,我可以在运行时以某种方式检查路径中tools.jar
是否可用并在可用JAVA_HOME
时加载它吗?因为如果它不可用,我只想用 Sigar 进行正常监控,但如果它可用,我想使用 JMX 来监控 Java 应用程序。我的项目是一个 Maven 项目,我正在使用它maven-shade-plugin
来创建一个包含所有依赖项的可执行 jar。
目前我正在使用我在互联网上发现的一个肮脏的黑客,它使用反射将tools.jar
动态添加到系统类路径(如果存在)。但我想知道是否也可以以不同的方式进行操作?预先感谢您的支持。