前言
在開源世界中有很多優(yōu)秀的RPC框架,如gRpc,Dubbo,Motan等等,但在某些場景下,此類框架就顯得"太重",Spring全家桶是java程序猿的最愛,在rpc方面對多種模型提供了支持,如Hessisan,Burlap以及Http invoker。今天想聊一聊的是基于Spring的輕量級的RPC實現---Hessian捐腿。
Hessian是一種基于Http的輕量級遠程服務解決方案,利用二進制消息進行客戶端和服務端的交互,采用Servlet暴露服務乔宿。因它的二進制消息可以移植到其他非java語言中,具有跨語言特性。
Spring對RPC的支持及調用模型
- 不管選擇哪種遠程調用模型,在spring中都提供了風格一致的支持(通常是由一個代理工廠bean實現),如下圖访雪。
Hessian服務發(fā)布與調用
模塊架構
QQ截圖20180826110043.png
sb-hessian-client 服務接口定義
sb-hessian-consumer 服務調用方
sb-hessian-provider 服務提供方
服務接口定義
public interface HelloService {
String sayHello(String word);
}
服務實現與暴露
- 服務實現
> /**
>
> * 服務實現
>
> */
>
> @Component("helloService")
>
> public class HelloServiceImpl implements HelloService,Serializable {
>
> @Override
>
> public String sayHello(String word) {
>
> return "hessian" + word;
>
> }
>
> }
- 服務暴露
/**
* 服務暴露
* @param helloService
* @return
*/
@Bean(name = "/helloService.service")
public HessianServiceExporter exportService(@Autowired HelloService helloService) {
HessianServiceExporter exporter = new HessianServiceExporter();
exporter.setService(helloService);
exporter.setServiceInterface(HelloService.class);
return exporter;
}
- 服務調用
/**
* 外部依賴服務
*
* @return
*/
@Bean(name = "helloService")
public HessianProxyFactoryBean getHelloService() {
HessianProxyFactoryBean proxy = new HessianProxyFactoryBean();
proxy.setServiceUrl("http://localhost:8083/helloService.service");
proxy.setServiceInterface(HelloService.class);
return proxy;
}
注意
hessian是基于二進制的消息,在服務實現必須實現序列化接口详瑞。
-
關于HessianServiceExporter
HessianServiceExporter本質上是一個SpringMVC控制器。它通過接收Hessian請求,并把其轉換成對應的bean方法調用臣缀。
由setService()和setServiceInterface()暴露服務蛤虐。
-
關于HessianProxyFactoryBean
通過setServiceUrl()和setServiceInterface()獲取服務調用
setServiceUrl("http://localhost:8083/helloService.service");
注意這里需要指定的服務提供端的端口
> 項目示例鏈接
[鏈接](https://gitee.com/lingluojun/sb-rpc-parent.git)