springCloud(5)-RestTemplate
consumer-provider 之间一般通过 RestTemplate来进行数据交互。
1.官网
https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
2.使用
(Url,requestMap,ResponseBean.class)
请求地址、请求参数、HTTP响应转换被转换成的对象类型
3.config类编写,把RestTemplate加载进来
@Configuration
public class ApplicationContextConfig {
@Bean
//@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
注意:注解:@Configuration @Bean
以前spring 是xml配置,现在是注解了 //applicationContext.xml <bean id="" class="">
4.调用
url
post
get()带参数
public class OrderController {
//调用地址
// public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
public static final String PAYMENT_URL = "http://localhost:8001";
@Resource
private RestTemplate restTemplate;
//读操作 get
//多了一个consumer
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment)
{
//URL,参数,返回值
return restTemplate.postForObject(PAYMENT_URL +"/payment/create",payment,CommonResult.class);
}
//写操作 post
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id)
{
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
}
5.验证
5.1启动两个服务
5.2 provider: 浏览器输入网址看是否成功 http://localhost:8001/payment/get/31
5.3 consumer: 输入:http://localhost/consumer/payment/get/31
没写端口号,默认80.这个值是application.yml中配置的。


浙公网安备 33010602011771号