1. 程式人生 > >使用Spring的RmiServiceExporter釋出RMI服務設定registryHost報Connection refused to host問題解決

使用Spring的RmiServiceExporter釋出RMI服務設定registryHost報Connection refused to host問題解決

昨天我在使用spring的RmiServiceExporter釋出RMI服務的時候,設定了registryHost屬性,結果發現報下面這樣的錯誤,拒絕連線:

java.rmi.ConnectException:Connection refused to host:127.0.0.1
搞了好半天都沒能解決,後來看了下RmiServiceExporter的原始碼,發現:

當你不設定registryHost屬性的時候,原始碼中首先會建立一個Registry返回,類似於下圖的程式碼,

return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory);

當你設定了registryHost屬性的時候,原始碼中就不建立Registry,而是直接去獲取,可是我們自己也沒有建立,所以就會報連線不上,類似下面這個程式碼,

Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);

解決方案1:

寫個類繼承RmiServiceExporter,重寫其getRegistry的方法,然後使用你自己寫的這個類釋出RMI,如下所示:

@Override
protected Registry getRegistry(String registryHost, int registryPort, RMIClientSocketFactory clientSocketFactory,
RMIServerSocketFactory serverSocketFactory) throws RemoteException {


if (registryHost != null) {
// Host explictly specified: only lookup possible.
if (logger.isInfoEnabled()) {
logger.info("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]");
}
try {
//把spring原始碼中這裡try起來,報異常就建立一個
Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
testRegistry(reg);
return reg;
} catch (RemoteException ex) {
LocateRegistry.createRegistry(registryPort);
Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
testRegistry(reg);
return reg;
}
}


else {
return getRegistry(registryPort, clientSocketFactory, serverSocketFactory);
}
}

解決方法2:

不直接設定registryHost和registryPort屬性,自己寫個獲取Registry的工廠bean,賦值給RmiServiceExporter的reistry屬性。