其他分享
首页 > 其他分享> > Ribbon RestTemplate 的使用方法

Ribbon RestTemplate 的使用方法

作者:互联网

1

要想使用RestTemplate,需要添加配置类,注入bean

RestTemplate共有四类方法


代码实例(四个controller方法对应以上四个方法),CommonResult<>类和Payment类是我写的Vo和JavaBean

@RestController
public class OrderController {

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> postForObject(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getForObject(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class,id);
    }

    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getForEntity(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> res = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

        // 如果请求成功,返回内容
        if (res.getStatusCode().is2xxSuccessful()) {
            return res.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }

    @GetMapping("/consumer/payment/postForEntity")
    public CommonResult<Payment> postForEntity(Payment payment) {
        ResponseEntity<CommonResult> res = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
        if (res.getStatusCode().is2xxSuccessful()) {
            return res.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }
}

标签:CommonResult,res,RestTemplate,payment,id,return,方法,class,Ribbon
来源: https://www.cnblogs.com/acdongla/p/15800316.html