在Spring 中使用Http Invoker在官方文档中已经描述的很清楚了,那么,在Spring Boot中怎么使用呢?
首先我们定义一个接口:
public interface ITestService {
String test(byte[] hello);
}
Server
在Server中,我们要一个对外提供服务的url,平时我们都是使用@Controller和@RequestMapping这两个注解实现对外提供服务,其实这里面Spring MVC做了很多动作,才让我们这么简单的把服务对外提供。
首先我们提供上述接口的实现类:
@Service
public class TestServiceImpl implements ITestService {
@Override
public String test(byte[] world) {
return "测试成功!!!!!!" + new String(world, StandardCharsets.UTF_8);
}
}
在Spring Boot中,我们只需要这样配置即可得到一个对外提供服务的url:
@Configuration
public class ServerConfiguration {
@Bean("/testService")
public HttpInvokerServiceExporter testService(ITestService testService) {
HttpInvokerServiceExporter httpInvokerServiceExporter = new HttpInvokerServiceExporter();
httpInvokerServiceExporter.setService(testService);
httpInvokerServiceExporter.setServiceInterface(ITestService.class);
return httpInvokerServiceExporter;
}
}
很多人估计注意到了Bean的名字,为啥是“/”开头的?其实,在我们的Spring MVC中有一个很少用到的类:
org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
它的作用就是把Spring MVC上下文中以“/”开头的Bean进行对外提供服务(注:根据配置可以把祖先上下文中“/”开头的Bean进行对外提供服务,默认情况下Spring Boot只有一个上下文,有兴趣的小伙伴可以自行研究下)。
按照上述配置,服务路径就是Bean的名称(即:http://IP:PORT/【上下文】/testService)。
Client
在客户端中我们只需要调用Server端中这个接口的实现就好了。那么我们怎么调用到呢?代码如下:
@Configuration
public class ClientConfiguration {
@Value("${test.service.url}")
private String testServiceUrl;
@Bean
public HttpInvokerProxyFactoryBean testService() {
HttpInvokerProxyFactoryBean httpInvokerProxyFactoryBean = new HttpInvokerProxyFactoryBean();
httpInvokerProxyFactoryBean.setServiceUrl(testServiceUrl);
httpInvokerProxyFactoryBean.setServiceInterface(ITestService.class);
return httpInvokerProxyFactoryBean;
}
}
其实它就是一个远程服务的代理类。当你调用它的时候,它会去指定远程地址进行调用对应实现。
来我们测试一下
@Controller
public class TestController {
@Autowired
private ITestService testService;
@ResponseBody
@RequestMapping("test")
public String test() {
return testService.test("不知道在做啥!!".getBytes(StandardCharsets.UTF_8));
}
}
请求结果:
测试完成!
详细代码可参考本人码云:https://gitee.com/Big_Xin/spring-learn/tree/master/spring-http-invoker/spring-http-invoker-demo