【发布时间】:2016-03-29 20:26:06
【问题描述】:
我正在开发一个监控应用程序,它使用 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);
}
}
到目前为止,这工作正常,但问题是我现在依赖于来自 JDK 的 tools.jar。
我现在的问题是我可以在运行时以某种方式检查tools.jar 是否在JAVA_HOME 路径中可用并在它可用时加载它?因为如果它不可用,我只想用 Sigar 进行正常监控,但如果它可用,我想使用 JMX 来监控 Java 应用程序。
我的项目是一个 maven 项目,我正在使用 maven-shade-plugin 创建一个包含所有依赖项的可执行 jar。
目前我正在使用我在互联网上发现的一个肮脏的黑客,它使用反射将tools.jar 动态添加到系统类路径(如果存在)。但我想知道是否也可以以不同的方式进行操作?
提前感谢您的支持。
【问题讨论】:
-
这是个坏主意,尤其是因为这个 JAR 在 Java 9 中将消失。您应该使用 Compiler API 来访问
javac。
标签: java maven jvm jmx tools.jar