Spring 2 org.springframework.remoting 提供統一抽象,讓業務介面無感知切換底層協議:RMI、Hessian/Burlap(HTTP 二進制/XML)、HTTP Invoker(Java 序列化)。
public interface IBookService { Book getById(String id); }
public class Book { public String name, id, author; }
public class BookService implements IBookService {
public Book getById(String id) { return BookStore.getById(id); }
}
// 客戶端
public class BookQueryService {
private IBookService bookService;
public void setAccountService(IBookService s) { this.bookService = s; }
public Book getBookById(String id) { return bookService.getById(id); }
}
<bean id="bookService" class="com.xmatthew.spring.remote.BookService"/>
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName" value="bookService"/>
<property name="service" ref="bookService"/>
<property name="serviceInterface" value="com.xmatthew.spring.remote.IBookService"/>
<property name="registryPort" value="1800"/>
</bean>
<bean class="com.xmatthew.spring.remote.client.BookQueryService">
<property name="bookService" ref="bookService"/>
</bean>
<bean id="bookService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://localhost:1800/bookService"/>
<property name="serviceInterface" value="com.xmatthew.spring.remote.IBookService"/>
</bean>
需在 web.xml 配置 DispatcherServlet 映射 /remoting/*。
<bean name="/bookService" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="bookService"/>
<property name="serviceInterface" value="com.xmatthew.spring.remote.IBookService"/>
</bean>
<bean id="bookService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl" value="https://localhost:8080/remoting/bookService"/>
<property name="serviceInterface" value="com.xmatthew.spring.remote.IBookService"/>
</bean>
配置同 Hessian,僅將類名替換:
BurlapServiceExporter / BurlapProxyFactoryBean。
同樣需 DispatcherServlet。
<bean name="/bookService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="bookService"/>
<property name="serviceInterface" value="com.xmatthew.spring.remote.IBookService"/>
</bean>
<bean id="bookService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="https://localhost:8080/remoting/bookService"/>
<property name="serviceInterface" value="com.xmatthew.spring.remote.IBookService"/>
</bean>
| 協議 | 序列化 | 防火牆友好 | 跨語言 | 適用場景 |
|---|---|---|---|---|
| RMI | Java 原生 | 差(需開高埠) | 否 | 內網 Java 互調 |
| Hessian | 二進制 | 好(HTTP) | 是(多語言支援) | 高效能、跨語言 |
| Burlap | XML | 好 | 是 | 除錯、異構系統 |
| HTTP Invoker | Java 序列化 | 好 | 否 | Spring 生態內部調用 |