当订单去调用支付微服务的时候,订单模块不能够像支付模块一样,导入service对象进行操作。两个服务之间调用,在最原始的阶段,是HttpClint技术。之后用的便是封装了之后的RestTemplate。
是什么ji
RestTemplate提供了多种便捷访问远程Http服务的方法,
是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集
调用接口的封装
官网地址
https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
使用
使用restTemplate访问restful接口非常的简单粗暴无脑。
(url, requestMap, ResponseBean.class)这三个参数分别代表
REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
如果要在springboot项目中使用RestTemplate,需要把他注入到容器里面
新建一个config文件夹,在此文件夹下新建一个ApplicajitionContextConfig类,添加@Configution注解
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
添加了配置类之后,便可以在订单微服务的控制层使用
@Resource
private RestTemplate restTemplate;
@GetMapping("consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL +"/payment/create",payment,CommonResult.class);
}
resttemplate发送的是json体的body参数,接收端接受需要使用@requestbody注解接收