1. 概述
在之前題為“使用 HTTP 邀請人的 Spring Remoting 簡介”的文章中,我們瞭解到如何輕鬆設置一個利用遠程方法調用 (RMI) 的客户端/服務器應用程序,通過 Spring Remoting。
在本文中,我們將展示 Spring Remoting 如何支持使用 Hessian 和 Burlap 實現 RMI。
2. Maven 依賴項
Hessian 和 Burlap 都由以下庫提供,您需要在您的 pom.xml 文件中明確包含它:
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.38</version>
</dependency>您可以在 Maven 中央倉庫 找到最新版本。
3. Hessian
Hessian 是一種輕量級的二進制協議,由 Caucho 提供,該公司是 Resin 應用服務器的開發者。 Hessian 實現存在於多個平台和語言中,包括 Java。
在後續的子章節中,我們將修改之前文章中提出的“預訂出租車”示例,使其客户端和服務器使用 Hessian 協議進行通信,而不是基於 Spring Remote HTTP 的協議。
3.1. 暴露服務
通過配置一個 RemoteExporter,類型為 HessianServiceExporter,來替換之前使用的 HttpInvokerServiceExporter,暴露服務。
@Bean(name = "/booking")
RemoteExporter bookingService() {
HessianServiceExporter exporter = new HessianServiceExporter();
exporter.setService(new CabBookingServiceImpl());
exporter.setServiceInterface( CabBookingService.class );
return exporter;
}我們現在可以啓動服務器並保持其運行狀態,同時準備客户端。
3.2. 客户端應用程序
讓我們實現客户端。 同樣,修改非常簡單——我們需要將 HttpInvokerProxyFactoryBean 替換為 HessianProxyFactoryBean:
@Configuration
public class HessianClient {
@Bean
public HessianProxyFactoryBean hessianInvoker() {
HessianProxyFactoryBean invoker = new HessianProxyFactoryBean();
invoker.setServiceUrl("http://localhost:8080/booking");
invoker.setServiceInterface(CabBookingService.class);
return invoker;
}
public static void main(String[] args) throws BookingException {
CabBookingService service
= SpringApplication.run(HessianClient.class, args)
.getBean(CabBookingService.class);
out.println(
service.bookRide("13 Seagate Blvd, Key Largo, FL 33037"));
}
}現在讓我們運行客户端,使其通過 Hessian 與服務器建立連接。
4. burlap
burlap 是由 Caucho 開發的另一種輕量級協議,基於 XML。 Caucho 已經停止維護該協議,因此,其在最新版本的 Spring 發佈中已棄用,即使它仍然存在。
因此,您只有在您有已經部署並無法輕鬆遷移到其他 Spring Remoting 實現的應用時,才應繼續使用 burlap。
4.1. 暴露服務
我們可以完全以與使用 Burlap 相同的方式使用它——我們只需要選擇合適的實現:
@Bean(name = "/booking")
RemoteExporter burlapService() {
BurlapServiceExporter exporter = new BurlapServiceExporter();
exporter.setService(new CabBookingServiceImpl());
exporter.setServiceInterface( CabBookingService.class );
return exporter;
}正如您所見,我們已將導出器類型從 HessianServiceExporter 更改為 BurlapServiceExporter。所有設置代碼均可保持不變。
再次,讓我們啓動服務器,並在我們處理客户端時保持其運行。
<h3><strong>4.2. 客户端實現</strong></h3
<p>我們還可以將 <em >Hessian</em> 替換為 <em >Burlap</em> 在客户端進行更改,將 <em >HessianProxyFactoryBean</em> 替換為 <em >BurlapProxyFactoryBean</em>:</p>
@Bean
public BurlapProxyFactoryBean burlapInvoker() {
BurlapProxyFactoryBean invoker = new BurlapProxyFactoryBean();
invoker.setServiceUrl("http://localhost:8080/booking");
invoker.setServiceInterface(CabBookingService.class);
return invoker;
}我們現在可以運行客户端,並使用 Burlap 成功地查看它與服務器應用程序的連接情況。
5. 結論
通過這些簡短的示例,我們展示了使用 Spring Remoting 輕鬆選擇不同技術來實現遠程方法調用,以及您如何開發一個應用程序,而無需瞭解所使用的協議的技術細節。