前言
看了其他的文章发现,大多数都是只写了关键的部分,对于一个初学者来说只能明白用了什么东西,但实际动手发现,项目还存在一些问题,通过本篇文章,可以避免一些问题,节省一些时间成本。
Hessian简介
Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能。 相比WebService,Hessian更简单、快捷。采用的是二进制RPC协议,因为采用的是二进制协议,所以它很适合于发送二进制数据。
但是它的参数和返回值都需要实现Serializable接口。
代码实现
由于Hessian是一个远程调用的工具,那么我们需要创建2个springboot项目来模拟,服务端项目:springboot-hessian-server,客户端项目:springboot-hessian-client.
springboot-hessian-server端
application.properties
server.port=8081
server端pom.xml
com.caucho
hessian
4.0.38
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-maven-plugin
true
需要注意上面那个插件,默认的时候创建,但是没有下面中的内容,打包之后,反编译会发现根路径是BOOT-INF,这会引起客户端找不到接口中的方法的问题。
创建service接口
public interface HelloWorldService {
String sayHello(String name);
}
创建service实现类
@Service
public class HelloWorldServiceImpl implements HelloWorldService {
@Override
public String sayHello(String name) {
return "Hello world! "+ name;
}
}
Application类
@SpringBootApplication
public class TestSpringbootHessianApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringbootHessianApplication.class, args);
}
@Autowired
private HelloWorldService helloWorldService;
@Bean(name = "/hello/world/service")
public HessianServiceExporter accountService(){
HessianServiceExporter exporter = new HessianServiceExporter();
exporter.setService(helloWorldService);
exporter.setServiceInterface(HelloWorldService.class);
return exporter;
}
client端
application.properties
server.port=8082
pom.xml
com.caucho
hessian
4.0.38
org.springframework.boot
spring-boot-starter-web
com.test.springboot.hessian
test-hessian
0.0.1-SNAPSHOT
Application类
@SpringBootApplication
public class TestSpringbootHessianClientApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringbootHessianClientApplication.class, args);
}
@Bean
public HessianProxyFactoryBean helloClient(){
HessianProxyFactoryBean factoryBean = new HessianProxyFactoryBean();
factoryBean.setServiceUrl("http://localhost:8081/hello/world/service");
factoryBean.setServiceInterface(HelloWorldService.class);
return factoryBean;
}
}
controller
@RestController
public class HelloWorldController {
@Autowired
HelloWorldService helloWorldService;
@RequestMapping("/test")
public String test(){
return helloWorldService.sayHello("zzz");
}
}
将服务端的代码打包安装到本地仓库,打开浏览器输入 http://localhost:8082/test 即可。
附上本人的git地址: