RestTemplate是什么?
RestTemplate提供了多种便捷访问远程Http服务的方法,
是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集
直接上代码
下面展示一些 内联代码片
。
这个是被调用端Controller层
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@PostMapping(value = "/payment/create")
public CommonResult create(payment payment){
int result = paymentService.create(payment);
log.info("*****插入结果:"+result);
if (result>0){ //成功
return new CommonResult(200,"插入数据库成功",result);
}else {
return new CommonResult(444,"插入数据库失败",null);
}
}
@GetMapping(value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
payment payment = paymentService.getPaymentById(id);
log.info("*****查询结果:"+payment+"22");
if (payment!=null){ //说明有数据,能查询成功
return new CommonResult(200,"查询成功",payment);
}else {
return new CommonResult(444,"没有对应记录,查询ID:"+id,null);
}
}
}
在调用端要先写一个方法
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
在调用端的Controller层正式调用
@RestController
@Slf4j
public class OrderController {
//被调用服务的端口
public static final String PAYMENT_URL = "http://localhost:8001";
@Resource
private RestTemplate restTemplate; //注入上一个方法
@GetMapping("/consumer/payment/create")
public CommonResult<payment> create(payment payment){
//restTemplate.postForObject 三个参数REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class); //写操作
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<payment> getPayment(@PathVariable("id") Long id){
//restTemplate.getForObject 三个参数REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);//插入数据
}
}