2013-03-22 81 views
2

我正在嘗試啓用我的核心Java應用程序以通過JMX實現遠程訪問。然而,兩個限制使它比應該更難。以編程方式啓用遠程jmx監控

a)我不能隨意更改啓動Linux機器上應用程序的腳本。因此,我無法將任何「jmxremote」參數傳遞給jvm。

b)我指定的遠程端口(com.sun.management.jmxremote.port = xxxx)很可能未打開,我無法修改腳本以嘗試另一個打開的端口。我必須自動執行。

我試圖通過編寫一個類來設置所有必需的jmxremote參數以及找到一個「空閒」端口來解決這些限制。

public class JmxRemoteConnectionHelper{ 

    @Override 
    public void init() throws Exception{ 

     InetAddress address = InetAddress.getLocalHost(); 
     String ipAddress = address.getHostAddress(); 
     String hostname  = address.getHostName(); 
     String port   = String.valueOf(getFreePort()); 

     System.setProperty("java.rmi.server.hostname", ipAddress); 
     System.setProperty("com.sun.management.jmxremote", "true"); 
     System.setProperty("com.sun.management.jmxremote.authenticate", "false"); 
     System.setProperty("com.sun.management.jmxremote.ssl", "false"); 
     System.setProperty("com.sun.management.jmxremote.port", port ); 

    } 

    private final int getFreePort(){ 

     **//seedPort is passed in the constructor** 
     int freePort   = seedPort; 
     ServerSocket sSocket = null; 

     for(int i=ZERO; i<PORT_SCAN_COUNTER; i++){ 

      try{ 

       freePort  = freePort + i; 
       sSocket   = new ServerSocket(freePort); 

       //FOUND a free port.    
       break; 

      }catch(Exception e){ 
       //Log 

      }finally{ 

       if(sSocket != null){ 
        try{ 
          sSocket.close(); 
         sSocket = null; 
        }catch(Exception e){ 
        //Log 
        } 

       } 
      } 

     } 

     return freePort; 
    } 

} 

如下圖所示,我通過彈簧初始化它。

<bean id="JmxRemoteConnection" class="JmxRemoteConnectionHelper" init-method="init" /> 

<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean" depends-on="JmxRemoteConnection" /> 

<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false" > 
     <property name="assembler"  ref="assembler"/> 
     <property name="namingStrategy" ref="namingStrategy"/> 
     <property name="autodetect"  value="true"/> 
     <property name="server"   ref="mbeanServer"/> 
</bean> 

<bean id="jmxAttributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/> 

<bean id="assembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler"> 
     <property name="attributeSource" ref="jmxAttributeSource"/> 
</bean> 

<bean id="namingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy" lazy-init="true"> 
     <property name="attributeSource" ref="jmxAttributeSource"/> 
</bean> 

爲了測試,我在我的Windows機器上啓動應用程序。它啓動正確。但是,當我在相同方框上嘗試通過「遠程進程」(ip:port)調用JConsole時,我得到一個「連接被拒絕」消息在底部。

我懷疑JMX代理沒有看到我設置的任何遠程系統屬性。任何想法,提示等將不勝感激。

我正在使用JDK 1.6

回答

3

既然你已經在使用Spring,我想你應該看看如果使用ConnectorServerFactoryBean可以做你正在做的事情。我從來不需要啓動遠程JMX服務器,但看起來這就是那個對象可以爲你做的事情。

+0

謝謝,ConnectorServerFactoryBean的確是我所需要的。 – CaptainHastings 2013-03-22 15:28:51