Spring 在各種 RPC 實作上都提供了風格一致的支援,命名規律也很整齊:服務端一律叫 *ServiceExporter,客戶端一律叫 *ProxyFactoryBean。本文把 RMI、Hessian/Burlap、HTTP Invoker、JAX-WS 四種模型逐一走過,並比較各自的適用場景。(若用 JMS 做 RPC,對應的類別是 JmsInvokerServiceExporter 與 JmsInvokerProxyFactoryBean。)
RMI 的 API 早在 JDK 1.1 就存在。原生寫法步驟是:宣告繼承 java.rmi.Remote 的遠端介面、方法拋 RemoteException、提供繼承 UnicastRemoteObject 的實作(或用 rmic 產生 skeleton 與 stub),最後啟動 RMI registry 並註冊。
用 Spring 會簡單很多,只需要兩個類別:RmiServiceExporter 與 RmiProxyFactoryBean。介面與實作完全是 POJO,不必繼承任何東西:
package pac.testcase.ws;
public interface MyService {
public boolean inviteMeIn();
public String welcome();
}
package pac.testcase.ws.impl;
import pac.testcase.ws.MyService;
public class MyServiceImpl implements MyService {
public boolean inviteMeIn() {
return true;
}
public String welcome() {
return "Everybody is welcome!!";
}
}
服務端配置:
<bean id="myService" class="pac.testcase.ws.impl.MyServiceImpl" />
<bean class="org.springframework.remoting.rmi.RmiServiceExporter"
p:service-ref="myService"
p:serviceName="welcomeService"
p:serviceInterface="pac.testcase.ws.MyService" />
預設位址是 rmi://localhost:1099/name,註冊埠沿用 Registry.REGISTRY_PORT,需要時可用 setRegistryHost 與 setRegistryPort 調整。
客戶端把遠端服務代理成一個普通 bean:
<bean id="clientSideService"
class="org.springframework.remoting.rmi.RmiProxyFactoryBean"
p:serviceUrl="rmi://localhost:1099/welcomeService"
p:serviceInterface="pac.test.RemoteService" />
package pac.test;
public interface RemoteService {
public String welcome();
}
之後不必再寫 Naming.lookup,遠端呼叫變得透明:
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
RemoteService service = (RemoteService) context.getBean("clientSideService");
System.out.println(service.welcome());
RMI 簡單高效,但會遇到 Java 序列化版本相容問題,而且它不是基於 HTTP 的,防火牆前面常常卡住。
兩者都由 Caucho 提供,Hessian 是 Resin 的一部分,維護頻率一直不高,但仍有團隊在用(例如 C# 與 Java 互通)。
Hessian 是 binary transport protocol,差別在於它不用 Java 序列化,因此能與 C++、C#、Python、Ruby 等語言溝通;Burlap 基於 XML,跨語言同樣沒問題,代價是傳輸量更大,唯一好處是可讀性。
原生使用 Hessian 有四個步驟:定義 Java 介面作為公開 API、用 HessianProxyFactory 建立客戶端、撰寫服務實作、在 servlet 引擎中設定服務。Spring 環境下,服務端與客戶端都要加同一個相依:
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.33</version>
</dependency>
服務同樣由 DispatcherServlet 分發:
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
介面與實作:
package pac.king.common.rpc;
public interface MyHessianService {
public String justHadEnoughParties();
}
package pac.king.common.rpc.impl;
import pac.king.common.rpc.MyHessianService;
public class MyHessianServiceImpl implements MyHessianService {
public String justHadEnoughParties() {
return "Please save me..";
}
}
即使 spring-mvc.xml 裡已經用 RequestMapping 做過映射,仍可再掛一個 URL 給 Hessian:
<context:component-scan base-package="pac.king.controller" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>/service=myHessianService</value>
</property>
</bean>
導出服務:
<bean id="myHessianServiceImpl" class="pac.king.common.rpc.impl.MyHessianServiceImpl" />
<bean id="myHessianService"
class="org.springframework.remoting.caucho.HessianServiceExporter"
p:service-ref="myHessianServiceImpl"
p:serviceInterface="pac.king.common.rpc.MyHessianService" />
客戶端:
<bean id="myHessianClient"
class="org.springframework.remoting.caucho.HessianProxyFactoryBean"
p:serviceUrl="https://localhost:8080/runtrain/service"
p:serviceInterface="pac.test.HessianService" />
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
HessianService service = (HessianService) context.getBean("myHessianClient");
System.out.println(service.justHadEnoughParties());
Burlap 的設定幾乎相同,只要把 HessianServiceExporter 換成 BurlapServiceExporter、HessianProxyFactoryBean 換成 BurlapProxyFactoryBean。
可以把它理解成「基於 HTTP 的 RMI」:兩全其美,但有一個遺憾——它沒有原生實作,完全屬於 Spring,只能在 Spring 應用之間使用。
用到的兩個類別是 HttpInvokerServiceExporter 與 HttpInvokerProxyFactoryBean。服務端改一行就好:
<bean id="myHessianServiceImpl" class="pac.king.common.rpc.impl.MyHessianServiceImpl" />
<!--
<bean id="myHessianService"
class="org.springframework.remoting.caucho.HessianServiceExporter"
p:service-ref="myHessianServiceImpl"
p:serviceInterface="pac.king.common.rpc.MyHessianService" />
-->
<bean id="myHessianService"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter"
p:service-ref="myHessianServiceImpl"
p:serviceInterface="pac.king.common.rpc.MyHessianService" />
客戶端也只換 class:
<bean id="myHessianClient"
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"
p:serviceUrl="https://localhost:8080/runtrain/service"
p:serviceInterface="pac.test.HessianService" />
既保有 Java 序列化的效率,又解決了防火牆問題。不過也有人反映,用 Hessian 做跨語言溝通時,走 HTTP 並不等於自動解決防火牆——那通常是另一個層次的問題。
看過 Hessian 之後,難免覺得 Web Service 笨重。既然有 Hessian,何必再背 SOAP 的包袱?在 StackOverflow 上繞一圈,得到的答案大致是:
既然很多場景下 Web Service 被視為 standard option,那就來看怎麼用 Spring 導出 Endpoint。這裡有個真正的痛點:Endpoint 的生命週期由 JAX-WS runtime 管理,Spring context 裡的 bean 無法自動注入進去,而你要導出的方法偏偏又依賴 Spring 管的 bean。
兩個解法:SpringBeanAutowiringSupport 與 SimpleJaxWsServiceExporter。
前者適用於任何生命週期不由 Spring 管理的場景,只要繼承它,建構時就會依當前 web application context 完成注入:
/**
* This constructor performs injection on this instance,
* based on the current web application context.
*
* <p>Intended for use as a base class.
*
* @see #processInjectionBasedOnCurrentContext
*/
public SpringBeanAutowiringSupport() {
processInjectionBasedOnCurrentContext(this);
}
public static void processInjectionBasedOnCurrentContext(Object target) {
Assert.notNull(target, "Target object must not be null");
WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
if (cc != null) {
AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
bpp.processInjection(target);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Current WebApplicationContext is not available for processing of "
+ ClassUtils.getShortName(target.getClass()) + ": "
+ "Make sure this class gets constructed in a Spring web application. "
+ "Proceeding without injection.");
}
}
}
於是 Endpoint 可以這樣寫:
@Service
@WebService(serviceName = "testMyService")
public class MyServiceEndpoint extends SpringBeanAutowiringSupport {
@Autowired
MyService myService;
@WebMethod
public String sayHiFarAway(String name) {
return myService.sayHiTo(name);
}
}
發布:
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext*.xml");
Endpoint.publish("https://localhost:8080/myservices",
(MyServiceEndpoint) context.getBean(MyServiceEndpoint.class));
呼叫:
javax.xml.ws.Service service = javax.xml.ws.Service.create(
url, new QName("https://endpoint.king.pac/", "testMyService"));
QName q = new QName("https://endpoint.king.pac/", "MyServiceEndpointPort");
MyClientService client = service.getPort(q, MyClientService.class);
System.out.println(client.sayHiFarAway("King"));
為了寫一個 Endpoint 還得繼承一個與業務無關的類別,發布與呼叫也繁瑣。改用 SimpleJaxWsServiceExporter 只要一行配置,它會自動偵測所有標了 @WebService 的類別,位址預設走 localhost:8080:
<bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter" />
但要注意它的前提:
Note that this exporter will only work if the JAX-WS runtime actually supports publishing with an address argument, i.e. if the JAX-WS runtime ships an internal HTTP server. This is the case with the JAX-WS runtime that's included in Sun's JDK 1.6 but not with the standalone JAX-WS 2.1 RI.
客戶端改用 JaxWsPortProxyFactoryBean,之後就能像普通 bean 一樣使用:
<bean id="clientSide"
class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean"
p:wsdlDocumentUrl="https://localhost:8080/testMyService?wsdl"
p:serviceName="testMyService"
p:portName="MyServiceEndpointPort"
p:serviceInterface="pac.king.endpoint.MyClientService"
p:namespaceUri="https://endpoint.king.pac/" />
MyClientService client = (MyClientService) context.getBean("clientSide");
System.out.println(client.sayHiFarAway("King"));
方便是方便,但改變不了一個事實:
Web service requests are larger than requests encoded with a binary protocol.
再加上 http/https 的種種限制,若處理不當,你得額外做很多 HTTP 本身做不到的事——而這種時候,RMI 反而最合適。
純 Java 內網、追求效能,RMI 或 HTTP Invoker;需要跨語言又走 HTTP,Hessian;要對接標準化生態系與既有 SOA 基礎設施,JAX-WS。沒有絕對最佳,只有與場景最贴合的那一個。