spring cloud+spring boot环境下使用RestTemplate实现2个微服务之间的调用

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);//插入数据
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值