第11課、RestTemplate

1 概述

spring框架提供的RestTemplate類可用於在應用中調用rest服務,它簡化了與http服務的通信方式,統一了RESTful的標準,封裝了http鏈接, 我們只需要傳入url及返回值類型即可。相較於之前常用的HttpClient,RestTemplate是一種更優雅的調用RESTful服務的方式。

在Spring應用程序中訪問第三方REST服務與使用Spring RestTemplate類有關。RestTemplate類的設計原則與許多其他Spring *模板類(例如JdbcTemplate、JmsTemplate)相同,為執行復雜任務提供了一種具有默認行為的簡化方法。

RestTemplate默認依賴JDK提供http連接的能力(HttpURLConnection),如果有需要的話也可以通過setRequestFactory方法替換為例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。

考慮到RestTemplate類是為調用REST服務而設計的,因此它的主要方法與REST的基礎緊密相連就不足為奇了,後者是HTTP協議的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,RestTemplate類具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。

2 在cloud裡面怎麼使用

2.1在具體的boot中增加一個配置類,可以聲明TestTemplate類

<code>@Configurable
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}/<code>

2.2 在controller中 像使用service一樣使用即可

<code>    public static final String URL_PREFIX = "http://localhost:8001/";

@Resource
private RestTemplate restTemplate;

@GetMapping("/client/create")
public CommonResult create(Payment payment){
return restTemplate.postForObject(URL_PREFIX+"/payment/create/",payment,CommonResult.class);
}


@GetMapping("/client/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
return restTemplate.getForObject(URL_PREFIX+"/payment/get/"+id,CommonResult.class);
}/<code>

測試


SpringCloud實戰 - 第11課、RestTemplate


分享到:


相關文章: