Ribbon RestTemplate 的使用方法

1

要想使用RestTemplate,需要添加配置类,注入bean
Ribbon RestTemplate 的使用方法

RestTemplate共有四类方法

  • getForObject(url, class)
    发送get请求,返回值为class
  • postForObject(url, javabean, class)
    发送post请求,请求参数是JavaBean,返回值为class
  • getForEntity(url, class)
    发送get请求,返回包装过的class
  • postForEntity(url, javabean, class)
    发送post请求, 请求参数是JavaBean,返回包装过的class

代码实例(四个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, "操作失败");
        }
    }
}
上一篇:Feign Ribbon Hystrix 关系剖析


下一篇:【无标题】