rmi穿越防火牆
阿新 • • 發佈:2019-01-26
前段時間寫了一個全文檢索服務,用的是RMI遠端呼叫。在本機上寫好後,測試ok.但一部署到伺服器上就報找不到服務。在網上找了一大通:
原因如下:
RMI除了註冊埠外,其通訊埠是伺服器隨機產生的,因此不容易穿過防火牆。
現將我在網上搜索到的解決方法公佈在這裡,給其它人需要的人一個方便。也給自己一個方便。
如果要扣分就扣吧。
一、普通解決:
- import java.rmi.server.*;
- import java.io.*;
- import java.net.*;
- publicclass SMRMISocket extends RMISocketFactory {
- public Socket createSocket(String host, int port)
- throws IOException{
- returnnew Socket(host,port);
- }
- public ServerSocket createServerSocket(int port)
- throws IOException {
- if (port == 0)
- port = 2098;//不指定就隨機
- returnnew ServerSocket(port);
- }
- }
import java.rmi.server.*; import java.io.*; import java.net.*; public class SMRMISocket extends RMISocketFactory { public Socket createSocket(String host, int port) throws IOException{ return new Socket(host,port); } public ServerSocket createServerSocket(int port) throws IOException { if (port == 0) port = 2098;//不指定就隨機 return new ServerSocket(port); } }
二、Spring中
- <bean id="rmiSearchService"class="org.springframework.remoting.rmi.RmiServiceExporter">
- <property name="serviceName" value="search"/><!-- 服務名稱 -->
- <property name="service" ref="searchService"/>
- <property name="serviceInterface" value="velcro.searchengine.ISearcher"
- <property name="registryPort" value="2098"/><!-- 埠 -->
- <property name="servicePort" value="2098"/>><!--不指定就隨機 -->
- </bean>