前言
在开源世界中有很多优秀的RPC框架,如gRpc,Dubbo,Motan等等,但在某些场景下,此类框架就显得"太重",Spring全家桶是java程序猿的最爱,在rpc方面对多种模型提供了支持,如Hessisan,Burlap以及Http invoker。今天想聊一聊的是基于Spring的轻量级的RPC实现---Hessian。
Hessian是一种基于Http的轻量级远程服务解决方案,利用二进制消息进行客户端和服务端的交互,采用Servlet暴露服务。因它的二进制消息可以移植到其他非java语言中,具有跨语言特性。
Spring对RPC的支持及调用模型
- 不管选择哪种远程调用模型,在spring中都提供了风格一致的支持(通常是由一个代理工厂bean实现),如下图。
Hessian服务发布与调用
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)
网友评论