一、背景介紹
在微服務都是以HTTP接口的形式暴露自身服務的,因此在調用遠程服務時就必須使用HTTP客戶端。我們可以使用JDK原生的URLConnection、Apache的Http Client、Netty的異步HTTP Client, Spring的RestTemplate。
這里介紹的是RestTemplate。RestTemplate底層用還是HttpClient,對其做了封裝,使用起來更簡單。
1、什么是RestTemplate?
RestTemplate是Spring提供的用于訪問Rest服務的客戶端,RestTemplate提供了多種便捷訪問遠程Http服務的方法,能夠大大提高客戶端的編寫效率。
調用RestTemplate的默認構造函數,RestTemplate對象在底層通過使用java.net包下的實現創建HTTP 請求,可以通過使用ClientHttpRequestFactory指定不同的HTTP請求方式。
ClientHttpRequestFactory接口主要提供了兩種實現方式
1、一種是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)創建底層的Http請求連接。
2、一種方式是使用HttpComponentsClientHttpRequestFactory方式,底層使用HttpClient訪問遠程的Http服務,使用HttpClient可以配置連接池和證書等信息。
其實spring并沒有真正的去實現底層的http請求(3次握手),而是集成了別的http請求,spring只是在原有的各種http請求進行了規范標準,讓開發者更加簡單易用,底層默認用的是jdk的http請求。
2、RestTemplate的優缺點
- 優點:連接池、超時時間設置、支持異步、請求和響應的編解碼
- 缺點:依賴別的spring版塊、參數傳遞不靈活
RestTemplate默認是使用SimpleClientHttpRequestFactory,內部是調用jdk的HttpConnection,默認超時為-1
1
2
3
4
|
@Autowired RestTemplate simpleRestTemplate; @Autowired RestTemplate restTemplate; |
二、配置RestTemplate
1、引入依賴
1
2
3
4
5
6
7
8
9
|
< dependency > < groupId >org.apache.httpcomponents</ groupId > < artifactId >httpclient</ artifactId > < version >4.5.6</ version > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > |
2、連接池配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#最大連接數 http.maxTotal: 100 #并發數 http.defaultMaxPerRoute: 20 #創建連接的最長時間 http.connectTimeout: 1000 #從連接池中獲取到連接的最長時間 http.connectionRequestTimeout: 500 #數據傳輸的最長時間 http.socketTimeout: 10000 #提交請求前測試連接是否可用 http.staleConnectionCheckEnabled: true #可用空閑連接過期時間,重用空閑連接時會先檢查是否空閑時間超過這個時間,如果超過,釋放socket重新建立 http.validateAfterInactivity: 3000000 |
3、初始化連接池
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package com.example.demo.config; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { @Value ( "${http.maxTotal}" ) private Integer maxTotal; @Value ( "${http.defaultMaxPerRoute}" ) private Integer defaultMaxPerRoute; @Value ( "${http.connectTimeout}" ) private Integer connectTimeout; @Value ( "${http.connectionRequestTimeout}" ) private Integer connectionRequestTimeout; @Value ( "${http.socketTimeout}" ) private Integer socketTimeout; @Value ( "${http.staleConnectionCheckEnabled}" ) private boolean staleConnectionCheckEnabled; @Value ( "${http.validateAfterInactivity}" ) private Integer validateAfterInactivity; @Bean public RestTemplate restTemplate() { return new RestTemplate(httpRequestFactory()); } @Bean public ClientHttpRequestFactory httpRequestFactory() { return new HttpComponentsClientHttpRequestFactory(httpClient()); } @Bean public HttpClient httpClient() { Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register( "http" , PlainConnectionSocketFactory.getSocketFactory()) .register( "https" , SSLConnectionSocketFactory.getSocketFactory()) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(maxTotal); // 最大連接數 connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); //單個路由最大連接數 connectionManager.setValidateAfterInactivity(validateAfterInactivity); // 最大空間時間 RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(socketTimeout) //服務器返回數據(response)的時間,超過拋出read timeout .setConnectTimeout(connectTimeout) //連接上服務器(握手成功)的時間,超出拋出connect timeout .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled) // 提交前檢測是否可用 .setConnectionRequestTimeout(connectionRequestTimeout) //從連接池中獲取連接的超時時間,超時間未拿到可用連接,會拋出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool .build(); return HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig) .setConnectionManager(connectionManager) .build(); } } |
4、使用示例
RestTemplate是對HttpCilent的封裝,所以,依HttpCilent然可以繼續使用HttpCilent。看下兩者的區別
HttpCilent:
1
2
3
4
5
6
7
8
|
@RequestMapping ( "/testHttpClient" ) @ResponseBody public Object getUser(String msg) throws IOException { CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpGet get = new HttpGet( "http://192.168.1.100:8080/User/getAllUser" ); CloseableHttpResponse response = closeableHttpClient.execute(get); return EntityUtils.toString(response.getEntity(), "utf-8" ); } |
RestTemplate:
1
2
3
4
5
6
|
@RequestMapping ( "/testRestTemplate" ) @ResponseBody public Object testRestTemplate() throws IOException { ResponseEntity result = restTemplate.getForEntity( "http://192.168.1.100:8080/User/getAllUser" ,ResponseEntity. class ; return result.getBody(); } |
RestTemplate更簡潔了。
三、RestTemplate常用方法
1、getForEntity
getForEntity方法的返回值是一個ResponseEntity<T>,ResponseEntity<T>是Spring對HTTP請求響應的封裝,包括了幾個重要的元素,如響應碼、contentType、contentLength、響應消息體等。比如下面一個例子:
1
2
3
4
5
6
7
8
9
10
11
12
|
@RequestMapping ( "/sayhello" ) public String sayHello() { ResponseEntity<String> responseEntity = restTemplate.getForEntity( "http://HELLO-SERVICE/sayhello?name={1}" , String. class , "張三" ); return responseEntity.getBody(); } @RequestMapping ( "/sayhello2" ) public String sayHello2() { Map<String, String> map = new HashMap<>(); map.put( "name" , "李四" ); ResponseEntity<String> responseEntity = restTemplate.getForEntity( "http://HELLO-SERVICE/sayhello?name={name}" , String. class , map); return responseEntity.getBody(); } |
2、getForObject
getForObject函數實際上是對getForEntity函數的進一步封裝,如果你只關注返回的消息體的內容,對其他信息都不關注,此時
可以使用getForObject,舉一個簡單的例子,如下:
1
2
3
4
5
|
@RequestMapping ( "/book2" ) public Book book2() { Book book = restTemplate.getForObject( "http://HELLO-SERVICE/getbook1" , Book. class ); return book; } |
3、postForEntity
1
2
3
4
5
6
7
|
@RequestMapping ( "/book3" ) public Book book3() { Book book = new Book(); book.setName( "紅樓夢" ); ResponseEntity<Book> responseEntity = restTemplate.postForEntity( "http://HELLO-SERVICE/getbook2" , book, Book. class ); return responseEntity.getBody(); } |
- 方法的第一參數表示要調用的服務的地址
- 方法的第二個參數表示上傳的參數
- 方法的第三個參數表示返回的消息體的數據類型
4、postForObject
如果你只關注,返回的消息體,可以直接使用postForObject。用法和getForObject一致。
5、postForLocation
postForLocation也是提交新資源,提交成功之后,返回新資源的URI,postForLocation的參數和前面兩種的參數基本一致,只不過該方法的返回值為Uri,這個只需要服務提供者返回一個Uri即可,該Uri表示新資源的位置。
6、PUT請求
在RestTemplate中,PUT請求可以通過put方法調用,put方法的參數和前面介紹的postForEntity方法的參數基本一致,只是put方法沒有返回值而已。舉一個簡單的例子,如下:
1
2
3
4
5
6
|
@RequestMapping ( "/put" ) public void put() { Book book = new Book(); book.setName( "紅樓夢" ); restTemplate.put( "http://HELLO-SERVICE/getbook3/{1}" , book, 99 ); } |
7、DELETE請求
1
2
3
4
5
|
delete請求我們可以通過delete方法調用來實現,如下例子: @RequestMapping ( "/delete" ) public void delete() { restTemplate.delete( "http://HELLO-SERVICE/getbook4/{1}" , 100 ); } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/Farrell_zeng/article/details/107086054