Spingboot集成Hessian实现远程调用服务
有这么一个使用场景,假如我们有多个模块都是一个单独的项目,不同模块有部署在不同的服务器上,相对都是一个个独立的块。那么我们如果从一个模块调用另一个模块该怎么办呢、有人说可以使用httpClient,得到JSON数据在处理,此办法可以的,但是过程中你要处理很多数据,比如解析JSON等。相对而言,hessian也是轻量级的 webService服务,好处是不需要关心过程,调用时就像调用本地一样,毕竟是RMI,httpClient的话,需要自己做好对象的解析。下面介绍如何在springboot中集成Hessian实现远程调用。
1、需要注意的地方:
- Hessian有服务端和客户端之分,服务端提供接口,客户端来调用
- 服务端和客户端有相同部分的代码,比如你想在服务器端返回一个USER对象,这个user对象的实体也要在客户端有。一般做法是把通用的部分打成jar包,服务端和客户端都引用它。打包和上传教程:https://vsalw.com/1775.html (也可以直接把公共部分安装到本地仓库,mvn clean install)然后服务端和客户端直接引用,引用的是jar包。
- 服务端和客户端都要引入Hessian的依赖
2、第一步新建一个spingboot项目,添加hessian的依赖
<dependency> <groupId>com.caucho</groupId> <artifactId>hessian</artifactId> <version>4.0.38</version> </dependency> |
3、服务端公共部分:此处比较简单只有一个接口和接口的实现类
//接口public interface DemoService { public String getName(String name); }//接口的实现类/@Service(“HelloWorldService”) public class DemoServiceImpl implements DemoService { @Override public String getName(String name) { return “欢迎你:” + name; } } |
4、服务端配置(此处配置在启动类了,也可以单独写一个配置类)
@SpringBootApplication public class DemoApplication { @Autowired private DemoService helloWorldService; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean(name = “/HelloWorldService”) public HessianServiceExporter accountService() { HessianServiceExporter exporter = new HessianServiceExporter(); exporter.setService(helloWorldService); exporter.setServiceInterface(DemoService.class); return exporter; } } |
到此,服务端已经结束 ,下面看客户端。
5、客户端:新建一个springboot项目,同样添加Hessian的依赖,此处省略依赖,上面有。
6、引入和服务端公共的部分,就是一个接口,如果返回对象,也需要加上和服务端的实体类,
public interface DemoService { public String getName(String name); } |
7、客户端配置类,主要是配置服务端的信息,地址,端口之类的
@SpringBootApplication public class DemoApplication {public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public HessianProxyFactoryBean helloClient() { HessianProxyFactoryBean factory = new HessianProxyFactoryBean(); factory.setServiceUrl(“http://localhost:8090/HelloWorldService”); factory.setServiceInterface(DemoService.class); return factory; } } |
8、配置好Bean后,就该怎么使用了,写一个常用的controller,自动装载刚刚配置的Bean,
@RestController public class TestController { @Autowired private DemoService helloWorldService; @RequestMapping(“/test”) public String test() { return helloWorldService.getName(“老王”); } } |
就这样,客户端就可以正常调用服务端了,可以直接返回对象的,无需关心中间序列化等过程。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。