RestTemplate使用不當引發的線上問題


轉自:https://www.jianshu.com/p/2d05397688dd

參考:https://www.cnblogs.com/jimw/p/9037542.html

背景

  • 系統: SpringBoot開發的Web應用;
  • ORM: JPA(Hibernate)
  • 接口功能簡述: 根據實體類ID到數據庫中查詢實體信息,然后使用RestTemplate調用外部系統接口獲取數據。

問題現象

  1. 瀏覽器頁面有時報504 GateWay Timeout錯誤,刷新多次后,則總是timeout
  2. 數據庫連接池報連接耗盡異常
  3. 調用外部系統時有時報502 Bad GateWay錯誤

分析過程

為便於描述將本系統稱為A,外部系統稱為B。

這三個問題環環相扣,導火索是第3個問題,然后導致第2個問題,最后導致出現第3個問題;
原因簡述: 第3個問題是由於Nginx負載下沒有掛系統B,導致本系統在請求外部系統時報502錯誤,而A沒有正確處理異常,導致http請求無法正常關閉,而springboot默認打開openInView, 導致調用A的請求關閉時才會關閉數據庫連接。

這里主要分析第1個問題:為什么請求A的連接出現504 Timeout.

AbstractConnPool

通過日志看到A在調用B時出現阻塞,直到timeout,打印出線程堆棧查看:

可以看到線程阻塞在AbstractConnPool類getPoolEntryBlocking方法中。

  1     private E getPoolEntryBlocking(
  2             final T route, final Object state,
  3             final long timeout, final TimeUnit timeUnit,
  4             final Future<E> future) throws IOException, InterruptedException, TimeoutException {
  5 
  6         Date deadline = null;
  7         if (timeout > 0) {
  8             deadline = new Date (System.currentTimeMillis() + timeUnit.toMillis(timeout));
  9         }
 10         this.lock.lock();
 11         try {
 12            //根據route獲取route對應的連接池
 13             final RouteSpecificPool<T, C, E> pool = getPool(route);
 14             E entry;
 15             for (;;) {
 16                 Asserts.check(!this.isShutDown, "Connection pool shut down");
 17                 for (;;) {
 18                    //獲取可用的連接
 19                     entry = pool.getFree(state);
 20                     if (entry == null) {
 21                         break;
 22                     }
 23                     // 判斷連接是否過期,如過期則關閉並從可用連接集合中刪除
 24                     if (entry.isExpired(System.currentTimeMillis())) {
 25                         entry.close();
 26                     }
 27                     if (entry.isClosed()) {
 28                         this.available.remove(entry);
 29                         pool.free(entry, false);
 30                     } else {
 31                         break;
 32                     }
 33                 }
 34                // 如果從連接池中獲取到可用連接,更新可用連接和待釋放連接集合
 35                 if (entry != null) {
 36                     this.available.remove(entry);
 37                     this.leased.add(entry);
 38                     onReuse(entry);
 39                     return entry;
 40                 }
 41 
 42                 // 如果沒有可用連接,則創建新連接
 43                 final int maxPerRoute = getMax(route);
 44                 // 創建新連接之前,檢查是否超過每個route連接池大小,如果超過,則刪除可用連接集合相應數量的連接(從總的可用連接集合和每個route的可用連接集合中刪除)
 45                 final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute);
 46                 if (excess > 0) {
 47                     for (int i = 0; i < excess; i++) {
 48                         final E lastUsed = pool.getLastUsed();
 49                         if (lastUsed == null) {
 50                             break;
 51                         }
 52                         lastUsed.close();
 53                         this.available.remove(lastUsed);
 54                         pool.remove(lastUsed);
 55                     }
 56                 }
 57 
 58                 if (pool.getAllocatedCount() < maxPerRoute) {
 59                    //比較總的可用連接數量與總的可用連接集合大小,釋放多余的連接資源
 60                     final int totalUsed = this.leased.size();
 61                     final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0);
 62                     if (freeCapacity > 0) {
 63                         final int totalAvailable = this.available.size();
 64                         if (totalAvailable > freeCapacity - 1) {
 65                             if (!this.available.isEmpty()) {
 66                                 final E lastUsed = this.available.removeLast();
 67                                 lastUsed.close();
 68                                 final RouteSpecificPool<T, C, E> otherpool = getPool(lastUsed.getRoute());
 69                                 otherpool.remove(lastUsed);
 70                             }
 71                         }
 72                        // 真正創建連接的地方
 73                         final C conn = this.connFactory.create(route);
 74                         entry = pool.add(conn);
 75                         this.leased.add(entry);
 76                         return entry;
 77                     }
 78                 }
 79 
 80                //如果已經超過了每個route的連接池大小,則加入隊列等待有可用連接時被喚醒或直到某個終止時間
 81                 boolean success = false;
 82                 try {
 83                     if (future.isCancelled()) {
 84                         throw new InterruptedException("Operation interrupted");
 85                     }
 86                     pool.queue(future);
 87                     this.pending.add(future);
 88                     if (deadline != null) {
 89                         success = this.condition.awaitUntil(deadline);
 90                     } else {
 91                         this.condition.await();
 92                         success = true;
 93                     }
 94                     if (future.isCancelled()) {
 95                         throw new InterruptedException("Operation interrupted");
 96                     }
 97                 } finally {
 98                     //如果到了終止時間或有被喚醒時,加出隊列,加入下次循環
 99                     pool.unqueue(future);
100                     this.pending.remove(future);
101                 }
102                 // 處理異常喚醒和超時情況
103                 if (!success && (deadline != null && deadline.getTime() <= System.currentTimeMillis())) {
104                     break;
105                 }
106             }
107             throw new TimeoutException("Timeout waiting for connection");
108         } finally {
109             this.lock.unlock();
110         }
111     }

從上面代碼中可以看出,getPoolEntryBlocking方法用於獲取連接,主要有三步:

  1. 檢查可用連接集合中是否有可重復使用的連接,如果有則獲取連接,返回
  2. 創建新連接,注意同時需要檢查可用連接集合(分為每個route的和全局的)是否有多余的連接資源,如果有,則需要釋放。
  3. 加入隊列等待

從線程堆棧可以看出,第1個問題是由於走到了第3步。開始時是有時會報504異常,刷新多次后會一直報504異常,經過跟蹤調試發現前幾次會成功獲取到連接,而連接池滿后,后面的請求會阻塞。正常情況下當前面的連接釋放到連接池后,后面的請求會得到連接資源繼續執行,可現實是后面的連接一直處於等待狀態,猜想可能是由於連接一直未釋放導致。

我們來看一下連接在什么時候會釋放。

RestTemplate

由於在調外部系統B時,使用的是RestTemplate的getForObject方法,從此入手跟蹤調試看一看。

 1     @Override
 2     public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
 3         RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
 4         HttpMessageConverterExtractor<T> responseExtractor =
 5                 new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
 6         return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
 7     }
 8 
 9     @Override
10     public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
11         RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
12         HttpMessageConverterExtractor<T> responseExtractor =
13                 new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
14         return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
15     }
16 
17     @Override
18     public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
19         RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
20         HttpMessageConverterExtractor<T> responseExtractor =
21                 new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
22         return execute(url, HttpMethod.GET, requestCallback, responseExtractor);
23     }

getForObject都調用了execute方法(其實RestTemplate的其它http請求方法調用的也是execute方法)

 1     @Override
 2     public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
 3             ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {
 4 
 5         URI expanded = getUriTemplateHandler().expand(url, uriVariables);
 6         return doExecute(expanded, method, requestCallback, responseExtractor);
 7     }
 8 
 9     @Override
10     public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
11             ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException {
12 
13         URI expanded = getUriTemplateHandler().expand(url, uriVariables);
14         return doExecute(expanded, method, requestCallback, responseExtractor);
15     }
16 
17     @Override
18     public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback,
19             ResponseExtractor<T> responseExtractor) throws RestClientException {
20 
21         return doExecute(url, method, requestCallback, responseExtractor);
22     }

所有execute方法都調用了同一個doExecute方法

 1     protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
 2             ResponseExtractor<T> responseExtractor) throws RestClientException {
 3 
 4         Assert.notNull(url, "'url' must not be null");
 5         Assert.notNull(method, "'method' must not be null");
 6         ClientHttpResponse response = null;
 7         try {
 8             ClientHttpRequest request = createRequest(url, method);
 9             if (requestCallback != null) {
10                 requestCallback.doWithRequest(request);
11             }
12             response = request.execute();
13             handleResponse(url, method, response);
14             if (responseExtractor != null) {
15                 return responseExtractor.extractData(response);
16             }
17             else {
18                 return null;
19             }
20         }
21         catch (IOException ex) {
22             String resource = url.toString();
23             String query = url.getRawQuery();
24             resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
25             throw new ResourceAccessException("I/O error on " + method.name() +
26                     " request for \"" + resource + "\": " + ex.getMessage(), ex);
27         }
28         finally {
29             if (response != null) {
30                 response.close();
31             }
32         }
33     }

doExecute方法創建了請求,然后執行,處理異常,最后關閉。可以看到關閉操作放在finally中,任何情況都會執行到,除非返回的response為null。

InterceptingClientHttpRequest

進入到request.execute()方法中,對應抽象類org.springframework.http.client.AbstractClientHttpRequest的execute方法

1     @Override
2     public final ClientHttpResponse execute() throws IOException {
3         assertNotExecuted();
4         ClientHttpResponse result = executeInternal(this.headers);
5         this.executed = true;
6         return result;
7     }
executeInternal方法是一個抽象方法,由子類實現(restTemplate內部的http調用實現方式有多種)。進入executeInternal方法,到達抽象類 org.springframework.http.client.AbstractBufferingClientHttpRequest
1     protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
2         byte[] bytes = this.bufferedOutput.toByteArray();
3         if (headers.getContentLength() < 0) {
4             headers.setContentLength(bytes.length);
5         }
6         ClientHttpResponse result = executeInternal(headers, bytes);
7         this.bufferedOutput = null;
8         return result;
9     }

此抽象類在AbstractClientHttpRequest基礎之上添加了緩沖功能,可以保存要發送給服務器的數據,然后一塊發送。看這一句:

1 ClientHttpResponse result = executeInternal(headers, bytes);
也是一個executeInternal方法,不過參數不同,它也是一個抽象方法。進入方法,到達 org.springframework.http.client.InterceptingClientHttpRequest
1     protected final ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
2         InterceptingRequestExecution requestExecution = new InterceptingRequestExecution();
3         return requestExecution.execute(this, bufferedOutput);
4     }

實例化了一個帶攔截器的請求執行對象InterceptingRequestExecution,進入看一看。

 1         public ClientHttpResponse execute(HttpRequest request, final byte[] body) throws IOException {
 2               // 如果有攔截器,則執行攔截器並返回結果
 3             if (this.iterator.hasNext()) {
 4                 ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
 5                 return nextInterceptor.intercept(request, body, this);
 6             }
 7             else {
 8                // 如果沒有攔截器,則通過requestFactory創建request對象並執行
 9                 ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
10                 for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
11                     List<String> values = entry.getValue();
12                     for (String value : values) {
13                         delegate.getHeaders().add(entry.getKey(), value);
14                     }
15                 }
16                 if (body.length > 0) {
17                     if (delegate instanceof StreamingHttpOutputMessage) {
18                         StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) delegate;
19                         streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
20                             @Override
21                             public void writeTo(final OutputStream outputStream) throws IOException {
22                                 StreamUtils.copy(body, outputStream);
23                             }
24                         });
25                      }
26                     else {
27                         StreamUtils.copy(body, delegate.getBody());
28                     }
29                 }
30                 return delegate.execute();
31             }
32         }

看一下RestTemplate的配置:

1         RestTemplateBuilder builder = new RestTemplateBuilder();
2         return builder
3                 .setConnectTimeout(customConfig.getRest().getConnectTimeOut())
4                 .setReadTimeout(customConfig.getRest().getReadTimeout())
5                 .interceptors(restTemplateLogInterceptor)
6                 .errorHandler(new ThrowErrorHandler())
7                 .build();
8     }

可以看到配置了連接超時,讀超時,攔截器,和錯誤處理器。
看一下攔截器的實現:

1     public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
2         // 打印訪問前日志
3         ClientHttpResponse execute = clientHttpRequestExecution.execute(httpRequest, bytes);
4         if (如果返回碼不是200) {
5             // 拋出自定義運行時異常
6         }
7         // 打印訪問后日志
8         return execute;
9     }

可以看到當返回碼不是200時,拋出異常。還記得RestTemplate中的doExecute方法吧,此處如果拋出異常,雖然會執行doExecute方法中的finally代碼,但由於返回的response為null(其實是有response的),沒有關閉response,所以這里不能拋出異常,如果確實想拋出異常,可以在錯誤處理器errorHandler中拋出,這樣確保response能正常返回和關閉。

RestTemplate源碼部分解析

何時如何決定使用哪一個底層http框架

知道了原因,我們再來看一下RestTemplate在什么時候決定使用什么http框架。其實在通過RestTemplateBuilder實例化RestTemplate對象時就決定了。
看一下RestTemplateBuilder的build方法

1     public RestTemplate build() {
2         return build(RestTemplate.class);
3     }
4     public <T extends RestTemplate> T build(Class<T> restTemplateClass) {
5         return configure(BeanUtils.instantiate(restTemplateClass));
6     }

可以看到在實例化RestTemplate對象之后,進行配置。

 1     public <T extends RestTemplate> T configure(T restTemplate) {
 2                // 配置requestFactory
 3         configureRequestFactory(restTemplate);
 4               // 配置消息轉換器
 5         if (!CollectionUtils.isEmpty(this.messageConverters)) {
 6             restTemplate.setMessageConverters(
 7                     new ArrayList<HttpMessageConverter<?>>(this.messageConverters));
 8         }
 9                //配置uri模板處理器
10         if (this.uriTemplateHandler != null) {
11             restTemplate.setUriTemplateHandler(this.uriTemplateHandler);
12         }
13               //配置錯誤處理器
14         if (this.errorHandler != null) {
15             restTemplate.setErrorHandler(this.errorHandler);
16         }
17               // 設置根路徑(一般為'/')
18         if (this.rootUri != null) {
19             RootUriTemplateHandler.addTo(restTemplate, this.rootUri);
20         }
21               // 配置登錄驗證
22         if (this.basicAuthorization != null) {
23             restTemplate.getInterceptors().add(this.basicAuthorization);
24         }
25               //配置自定義restTemplate器
26         if (!CollectionUtils.isEmpty(this.restTemplateCustomizers)) {
27             for (RestTemplateCustomizer customizer : this.restTemplateCustomizers) {
28                 customizer.customize(restTemplate);
29             }
30         }
31               //配置攔截器
32         restTemplate.getInterceptors().addAll(this.interceptors);
33         return restTemplate;
34     }

看一下方法的第一行,配置requestFactory。

 1     private void configureRequestFactory(RestTemplate restTemplate) {
 2         ClientHttpRequestFactory requestFactory = null;
 3         if (this.requestFactory != null) {
 4             requestFactory = this.requestFactory;
 5         }
 6         else if (this.detectRequestFactory) {
 7             requestFactory = detectRequestFactory();
 8         }
 9         if (requestFactory != null) {
10             ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary(
11                     requestFactory);
12             for (RequestFactoryCustomizer customizer : this.requestFactoryCustomizers) {
13                 customizer.customize(unwrappedRequestFactory);
14             }
15             restTemplate.setRequestFactory(requestFactory);
16         }
17     }

可以指定requestFactory,也可以自動探測。看一下detectRequestFactory方法。

 1     private ClientHttpRequestFactory detectRequestFactory() {
 2         for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES
 3                 .entrySet()) {
 4             ClassLoader classLoader = getClass().getClassLoader();
 5             if (ClassUtils.isPresent(candidate.getKey(), classLoader)) {
 6                 Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(),
 7                         classLoader);
 8                 ClientHttpRequestFactory requestFactory = (ClientHttpRequestFactory) BeanUtils
 9                         .instantiate(factoryClass);
10                 initializeIfNecessary(requestFactory);
11                 return requestFactory;
12             }
13         }
14         return new SimpleClientHttpRequestFactory();
15     }

循環REQUEST_FACTORY_CANDIDATES集合,檢查classpath類路徑中是否存在相應的jar包,如果存在,則創建相應框架的封裝類對象。如果都不存在,則返回使用JDK方式實現的RequestFactory對象。

看一下REQUEST_FACTORY_CANDIDATES集合

 1     private static final Map<String, String> REQUEST_FACTORY_CANDIDATES;
 2 
 3     static {
 4         Map<String, String> candidates = new LinkedHashMap<String, String>();
 5         candidates.put("org.apache.http.client.HttpClient",
 6                 "org.springframework.http.client.HttpComponentsClientHttpRequestFactory");
 7         candidates.put("okhttp3.OkHttpClient",
 8                 "org.springframework.http.client.OkHttp3ClientHttpRequestFactory");
 9         candidates.put("com.squareup.okhttp.OkHttpClient",
10                 "org.springframework.http.client.OkHttpClientHttpRequestFactory");
11         candidates.put("io.netty.channel.EventLoopGroup",
12                 "org.springframework.http.client.Netty4ClientHttpRequestFactory");
13         REQUEST_FACTORY_CANDIDATES = Collections.unmodifiableMap(candidates);
14     }

可以看到共有四種Http調用實現方式,在配置RestTemplate時可指定,並在類路徑中提供相應的實現jar包。

Request攔截器的設計

再看一下InterceptingRequestExecution類的execute方法。

 1   public ClientHttpResponse execute(HttpRequest request, final byte[] body) throws IOException {
 2         // 如果有攔截器,則執行攔截器並返回結果
 3       if (this.iterator.hasNext()) {
 4             ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
 5             return nextInterceptor.intercept(request, body, this);
 6         }
 7         else {
 8          // 如果沒有攔截器,則通過requestFactory創建request對象並執行
 9             ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
10             for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
11                 List<String> values = entry.getValue();
12                 for (String value : values) {
13                     delegate.getHeaders().add(entry.getKey(), value);
14                 }
15             }
16             if (body.length > 0) {
17                 if (delegate instanceof StreamingHttpOutputMessage) {
18                     StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) delegate;
19                     streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
20                         @Override
21                         public void writeTo(final OutputStream outputStream) throws IOException {
22                             StreamUtils.copy(body, outputStream);
23                         }
24                     });
25                }
26                else {
27                 StreamUtils.copy(body, delegate.getBody());
28                }
29             }
30             return delegate.execute();
31         }
32    }
大家可能會有疑問,傳入的對象已經是request對象了,為什么在沒有攔截器時還要再創建一遍request對象呢?
其實傳入的request對象在有攔截器的時候是 InterceptingClientHttpRequest對象,沒有攔截器時,則直接是包裝了各個http調用實現框的Request。如 HttpComponentsClientHttpRequestOkHttp3ClientHttpRequest等。當有攔截器時,會執行攔截器,攔截器可以有多個,而這里 this.iterator.hasNext()不是一個循環,為什么呢?秘密在於攔截器的intercept方法。
1 ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
2       throws IOException;

此方法包含request,body,execution。exection類型為ClientHttpRequestExecution接口,上面的InterceptingRequestExecution便實現了此接口,這樣在調用攔截器時,傳入exection對象本身,然后再調一次execute方法,再判斷是否仍有攔截器,如果有,再執行下一個攔截器,將所有攔截器執行完后,再生成真正的request對象,執行http調用。

那如果沒有攔截器呢?
上面已經知道RestTemplate在實例化時會實例化RequestFactory,當發起http請求時,會執行restTemplate的doExecute方法,此方法中會創建Request,而createRequest方法中,首先會獲取RequestFactory

 1 // org.springframework.http.client.support.HttpAccessor
 2 protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
 3    ClientHttpRequest request = getRequestFactory().createRequest(url, method);
 4    if (logger.isDebugEnabled()) {
 5       logger.debug("Created " + method.name() + " request for \"" + url + "\"");
 6    }
 7    return request;
 8 }
 9 
10 
11 // org.springframework.http.client.support.InterceptingHttpAccessor
12 public ClientHttpRequestFactory getRequestFactory() {
13    ClientHttpRequestFactory delegate = super.getRequestFactory();
14    if (!CollectionUtils.isEmpty(getInterceptors())) {
15       return new InterceptingClientHttpRequestFactory(delegate, getInterceptors());
16    }
17    else {
18       return delegate;
19    }
20 }

看一下RestTemplate與這兩個類的關系就知道調用關系了。

而在獲取到RequestFactory之后,判斷有沒有攔截器,如果有,則創建 InterceptingClientHttpRequestFactory對象,而此RequestFactory在createRequest時,會創建 InterceptingClientHttpRequest對象,這樣就可以先執行攔截器,最后執行創建真正的Request對象執行http調用。

 

獲取http連接邏輯流程圖

以HttpComponents為底層Http調用實現的邏輯流程圖。

流程圖說明:

  1. RestTemplate可以根據配置來實例化對應的RequestFactory,包括apache httpComponents、OkHttp3、Netty等實現。
  2. RestTemplate與HttpComponents銜接的類是HttpClient,此類是apache httpComponents提供給用戶使用,執行http調用。HttpClient是創建RequestFactory對象時通過HttpClientBuilder實例化的,在實例化HttpClient對象時,實例化了HttpClientConnectionManager和多個ClientExecChainHttpRequestExecutorHttpProcessor以及一些策略。
  3. 當發起請求時,由requestFactory實例化httpRequest,然后依次執行ClientexecChain,常用的有四種:
  • RedirectExec: 請求跳轉;根據上次響應結果和跳轉策略決定下次跳轉的地址,默認最大執行50次跳轉;
  • RetryExec:決定出現I/O錯誤的請求是否再次執行
  • ProtocolExec: 填充必要的http請求header,處理http響應header,更新會話狀態
  • MainClientExec:請求執行鏈中最后一個節點;從連接池CPool中獲取連接,執行請求調用,並返回請求結果;
  1. PoolingHttpClientConnectionManager用於管理連接池,包括連接池初始化,獲取連接,獲取連接,打開連接,釋放連接,關閉連接池等操作。
  2. CPool代表連接池,但連接並不保存在CPool中;CPool中維護着三個連接狀態集合:leased(租用的,即待釋放的)/available(可用的)/pending(等待的),用於記錄所有連接的狀態;並且維護着每個Route對應的連接池RouteSpecificPool;
  3. RouteSpecificPool是連接真正存放的地方,內部同樣也維護着三個連接狀態集合,但只記錄屬於本route的連接。
    HttpComponents將連接按照route划分連接池,有利於資源隔離,使每個route請求相互不影響;

總結

  • 在使用框架時,特別是在增強其功能,自定義行為時,要考慮到自定義行為對框架原有流程邏輯的影響,並且最好要熟悉框架相應功能的設計意圖。
  • 在與外部事物交互,包括網絡,磁盤,數據庫等,做到異常情況的處理。

 

restTemplate踩過的坑-spring clound

現在公司項目基本都從臃腫的項目轉換成微服務的方向轉換,因此也從中使用了spring clound的一些組件,在此過程中就遇到了restTemplate的坑。

起初,是直接注入RestTemplate,后來則不斷的遇到錯誤日志無法請求,出現異常。

異常信息:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No instances available for IP
意思是說url必須是服務的名稱,猜測應該是涉及到eureka,直接用ip跟url調用是直接報錯的。

因此不適用默認的,直接重新自定義,則引用了原有的注入修改一下。

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
/**
  *
  * 功能描述:
  *
  * @作者 jimw 創建時間:2018-04
  *
  */
@Configuration
public  class  RestTemplateConfig {
 
     public  RestTemplate restTemplate() {
         return  new  RestTemplate(getClientHttpRequestFactory());
     }
 
     /**
      * 配置HttpClient超時時間
      *
      * @return
      */
     private  ClientHttpRequestFactory getClientHttpRequestFactory() {
         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_SOCKET_TIMEOUT)
                 .setConnectTimeout(HTTP_CONNECT_TIMEOUT).build();
         CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
         return  new  HttpComponentsClientHttpRequestFactory(client);
     }
 
     /** http請求socket連接超時時間,毫秒為單位 */
     public  static  final  int  HTTP_SOCKET_TIMEOUT =  15000 ;
 
     /** http請求連接超時時間,毫秒為單位 */
     public  static  final  int  HTTP_CONNECT_TIMEOUT =  15000 ;
}

  

當配置了這個之后,服務正常了。觀察了一段時間,發現在並發的高峰期,開多幾個服務器負載,也會存在服務出現請求非常慢,導致接口出現阻塞的情況出現,經過分析

1、出現阻塞的原因是因為高峰並發的時候,出現請求的鏈接數很大

因此找了源碼,發現是因為restTemplate的默認配置值小於請求的鏈接數,而且路由並發也是默認為5的,因為微服務之間的邏輯處理中也有一定的時間。出現大規模阻塞的坑就這么踩到了。 

 

 

對代碼改造一下,配置最大鏈接數,路由並發數,這個restTemplate的坑就這么解決了。

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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package  com.jingbei.guess.config.web;
 
import  java.security.KeyManagementException;
import  java.security.KeyStoreException;
import  java.security.NoSuchAlgorithmException;
import  java.security.cert.CertificateException;
import  java.security.cert.X509Certificate;
 
import  javax.net.ssl.HostnameVerifier;
import  javax.net.ssl.SSLContext;
 
import  org.apache.http.client.HttpClient;
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.NoopHostnameVerifier;
import  org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import  org.apache.http.conn.ssl.SSLContextBuilder;
import  org.apache.http.conn.ssl.TrustStrategy;
import  org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import  org.apache.http.impl.client.HttpClientBuilder;
import  org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import  org.springframework.context.annotation.Bean;
import  org.springframework.context.annotation.Configuration;
import  org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import  org.springframework.web.client.DefaultResponseErrorHandler;
import  org.springframework.web.client.RestTemplate;
 
import  lombok.extern.slf4j.Slf4j;
 
/**
  *
  * 功能描述:
  *
  * @作者 jimw 創建時間: 2018-04
  *
  */
@Slf4j
@Configuration
public  class  RestTemplateConfig {
     @Bean
     public  RestTemplate restTemplate() {
         RestTemplate restTemplate =  new  RestTemplate();
         restTemplate.setRequestFactory(clientHttpRequestFactory());
         restTemplate.setErrorHandler( new  DefaultResponseErrorHandler());
         return  restTemplate;
     }
 
     @Bean
     public  HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
         try  {
             HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
             SSLContext sslContext =  new  SSLContextBuilder().loadTrustMaterial( null new  TrustStrategy() {
                 public  boolean  isTrusted(X509Certificate[] arg0, String arg1)  throws  CertificateException {
                     return  true ;
                 }
             }).build();
             httpClientBuilder.setSSLContext(sslContext);
             HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
             SSLConnectionSocketFactory sslConnectionSocketFactory =  new  SSLConnectionSocketFactory(sslContext,
                     hostnameVerifier);
             Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                     .register( "http" , PlainConnectionSocketFactory.getSocketFactory())
                     .register( "https" , sslConnectionSocketFactory).build(); // 注冊http和https請求
             // 開始設置連接池
             PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =  new  PoolingHttpClientConnectionManager(
                     socketFactoryRegistry);
             poolingHttpClientConnectionManager.setMaxTotal( 2700 );  // 最大連接數2700
             poolingHttpClientConnectionManager.setDefaultMaxPerRoute( 100 );  // 同路由並發數100
             httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
             httpClientBuilder.setRetryHandler( new  DefaultHttpRequestRetryHandler( 3 true ));  // 重試次數
             HttpClient httpClient = httpClientBuilder.build();
             HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =  new  HttpComponentsClientHttpRequestFactory(
                     httpClient);  // httpClient連接配置
             clientHttpRequestFactory.setConnectTimeout( 20000 );  // 連接超時
             clientHttpRequestFactory.setReadTimeout( 30000 );  // 數據讀取超時時間
             clientHttpRequestFactory.setConnectionRequestTimeout( 20000 );  // 連接不夠用的等待時間
             return  clientHttpRequestFactory;
         catch  (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
             log.error( "初始化HTTP連接池出錯" , e);
         }
         return  null ;
     }
 
}

  在對應的插件中配置即可

依賴包:

 1 <dependency>
 2 
 3 <groupId>org.apache.httpcomponents</groupId>
 4 
 5 <artifactId>httpclient</artifactId>
 6 
 7 <version>4.5.3</version>
 8 
 9 </dependency>
10 
11 <dependency>
12 
13 <groupId>org.apache.httpcomponents</groupId>
14 
15 <artifactId>httpcore</artifactId>
16 
17 <version>4.4.9</version>
18 
19 </dependency>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM