@Autowired
RestTemplateBuilder restTemplateBuilder;
@PostMapping("/order")
public String sayHello(){
RestTemplate rt=restTemplateBuilder.build();
System.
out
.println("开始创建订单");
rt.put("http://localhost:8081/repo/{1}",null,10001);
return "SUCCESS";
}
RepoController
@PutMapping("/repo/{pid}")
public void serverMsg(@PathVariable("pid") String pid){
System.
out
.println("扣减库存,商品 ID:"+pid);
}
简单了解 RestTemplate
服务于服务之间,一定不是相互隔离的,而是必须要相互联系进行数据通信才能实现完整的
功能。所以在刚刚的案例中,我们拆分出来的服务使用 RestTemplate 来进行远程通信。
在了解 RestTemplate 之前,先来简单了解下 HTTP Client,我们实现对于 http 服务的远程调
用,常见的手段是基于 Apache 提供的 HttpClient,或者是 Square 公司开源的 OkHttp。
还有 Netflix 公司提供的 Feign(feign 大家都比较熟悉,基于 spring cloud 开发的常见组件,
可以使得我们用面向接口的编程来实现远程调用)等等.
简单来说,RestTemplate 是 Spring 提供的用来访问 REST 服务的客户端,以前我们使用
Apache HttpClient 来进行远程调用时,需要写非常多的代码,还需要考虑各种资源回收的问
题。而 RestTemplate 简化了 Http 服务的通信,我们只需要提供 URL,RestTemplate 会帮我
们搞定一切。
另外,需要注意的是,RestTemplate 并没有重复造轮子,而是利用了现有的技术,如 JDK 或
Apache HttpClient 、OkHttp 等来实现 http 远程调用。
虽然 RestTemplate 已经是一个很不错的 HttpClient,但是目前 Spring Cloud 中仍然采用
Feign。对于易用性和可读性这块的优势更好。后续在讲微服务组件的时候会专门讲到
评论0
最新资源