我在将Jolokia与RMI-Service结合使用时遇到了问题。一旦启动RMI服务,就不再可以通过http访问Jolokia。
我创建了一个示例类来重现问题:
package com.example.rmi;
import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class RMITest {
private class RMIService extends UnicastRemoteObject {
private static final long serialVersionUID = 1L;
protected RMIService() throws RemoteException {
super();
}
public void doStuff() {
System.out.println("Processing...");
}
}
public static void main(String[] args) throws RemoteException {
RMITest rmiServer = new RMITest();
rmiServer.init();
}
private void init() throws RemoteException {
RMIService rmiService = new RMIService();
try {
System.out.println("Starting RMI-Service...");
String hostname = InetAddress.getLocalHost().getHostName();
System.setProperty("java.rmi.server.hostname", hostname);
int port = 2005;
LocateRegistry.createRegistry(port);
Naming.rebind("rmi://" + hostname + ":" + port
+ "/RMIService", rmiService);
System.out.println("RMI-Service started!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果我将主要方法更改为不启动RMI-Service,则可以再次通过http URL http://127.0.0.1:8778/jolokia/访问Jolokia:
public static void main(String[] args) throws RemoteException {
RMITest rmiServer = new RMITest();
//rmiServer.init();
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
该服务是一个可运行的jar。这是我用来启动应用程序的命令:
java -javaagent:jolokia-jvm-1.3.7-agent.jar=port=8778,host=localhost -jar RMITest-0.0.1-SNAPSHOT.jar
我从官方网站下载了jolokia代理:Jolokia Agent Download
答案 0 :(得分:0)
我通过在启动RMI-Service后以编程方式启动代理找到了一种解决方法。
以下Stackoverflow-Post中描述了如何执行此操作:Starting a Java agent after program start
所以我在运行init-method后启动了以下静态方法:
public static void attachGivenAgentToThisVM(String pathToAgentJar) {
try {
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(pathToAgentJar, "");
vm.detach();
} catch (Exception e) {
e.printStackTrace();
}
}
还有依赖于" tools.jar"必要的:
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
我仍然希望直接从命令行启动代理。因此,非常感谢更好的解决方案。