Spring 將遠程調用抽象為 Service Exporter(服務端)與 Proxy FactoryBean(客戶端)雙邊配置,POJO 業務邏輯零侵入即可發布為遠程服務。本文系統梳理四大協議配置要點、優缺點對比與選型建議。
public class Account implements Serializable { private String name; ... }
public interface AccountService {
void insertAccount(Account acc);
List getAccounts(String name);
}
public class AccountServiceImpl implements AccountService { ... }
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName" value="AccountService"/>
<property name="service" ref="accountService"/>
<property name="serviceInterface" value="example.AccountService"/>
<property name="registryPort" value="1199"/>
</bean>
<bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://HOST:1199/AccountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
特點: Java-to-Java、完整對象序列化、防火牆不友好(隨機端口)、無標準安全/事務傳播。
基於 HTTP + Java 序列化,穿透防火牆,仍限 Java-to-Java。
<bean name="/AccountService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
<bean id="httpInvokerProxy" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="https://remotehost:8080/AccountService"/>
<property name="serviceInterface" value="example.AccountService"/>
<!-- 可選:使用 Commons HttpClient -->
<property name="httpInvokerRequestExecutor">
<bean class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor"/>
</property>
</bean>
Caucho 開發,輕量高效,支持非 Java 客戶端(Python、PHP、C# 等)。
<bean name="/AccountService" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="accountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
<bean id="accountService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl" value="https://remotehost:8080/AccountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
配置同 Hessian,僅將類名替換為 BurlapServiceExporter/BurlapProxyFactoryBean。可讀性強但體積大、解析慢,**生產環境首選 Hessian**。
利用 Spring MVC 攔截器:
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="interceptors">
<list><ref bean="authorizationInterceptor"/></list>
</property>
</bean>
<bean id="authorizationInterceptor" class="org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor">
<property name="authorizedRoles">
<list><value>administrator</value><value>operator</value></list>
</property>
</bean>
生產建議接入 Spring Security / OAuth2 替代簡單角色攔截。
| 維度 | RMI | HTTP Invoker | Hessian/Burlap |
|---|---|---|---|
| 傳輸協議 | JRMP | HTTP | HTTP |
| 序列化 | Java 原生 | Java 原生 | Hessian 二進制 / XML |
| 跨語言 | ❌ | ❌ | ✅ |
| 防火牆友好 | ❌ | ✅ | ✅ |
| 複雜對象圖 | ✅ | ✅ | ⚠️ 延遲加載集合易失敗 |
| 事務傳播 | 需自定義 | 需自定義 | 不支持 |