2017-08-17 86 views
0

我在使用Jolokia與RMI服務一起使用時遇到問題。一旦RMI服務啓動,Jolokia不再可以通過http訪問。使用Jolokia代理與RMI服務器

我創建了一個例子類來重現問題:

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-服務,椒是通過HTTP URL http://127.0.0.1:8778/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 Agent Download

回答

0

我找到了一個解決方法通過在啓動代理啓動RMI-服務程序後, 。

它在以下#1 - 崗位描述如何做到這一點:在運行初始化方法後Starting a Java agent after program start

所以我在下面的靜態方法:

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> 

我還是喜歡直接從命令行啓動代理。所以更好的解決方案非常感謝。