RestTemplate使用不當引發的問題分析
背景
- 系統: SpringBoot開發的Web應用;
- ORM: JPA(Hibernate)
- 介面功能簡述: 根據實體類ID到資料庫中查詢實體資訊,然後使用RestTemplate呼叫外部系統介面獲取資料。
問題現象
- 瀏覽器頁面有時報504 GateWay Timeout錯誤,重新整理多次後,則總是timeout
- 資料庫連線池報連線耗盡異常
- 呼叫外部系統時有時報502 Bad GateWay錯誤
分析過程
為便於描述將本系統稱為A,外部系統稱為B。
這三個問題環環相扣,導火索是第3個問題,然後導致第2個問題,最後導致出現第3個問題;
原因簡述: 第3個問題是由於Nginx負載下沒有掛系統B,導致本系統在請求外部系統時報502錯誤,而A沒有正確處理異常,導致http請求無法正常關閉,而springboot預設開啟openInView, 只有呼叫A的請求關閉時才會關閉資料庫連線,而此時呼叫A的請求沒有關閉,導致資料庫連線沒有關閉。
這裡主要分析第1個問題:為什麼請求A的連接出現504 Timeout.
AbstractConnPool
通過日誌看到A在呼叫B時出現阻塞,直到timeout,打印出執行緒堆疊檢視:
可以看到執行緒阻塞在AbstractConnPool類getPoolEntryBlocking方法中。
private E getPoolEntryBlocking( final T route, final Object state, final long timeout, final TimeUnit timeUnit, final Future<E> future) throws IOException, InterruptedException, TimeoutException { Date deadline = null; if (timeout > 0) { deadline = new Date (System.currentTimeMillis() + timeUnit.toMillis(timeout)); } this.lock.lock(); try { //根據route獲取route對應的連線池 final RouteSpecificPool<T, C, E> pool = getPool(route); E entry; for (;;) { Asserts.check(!this.isShutDown, "Connection pool shut down"); for (;;) { //獲取可用的連線 entry = pool.getFree(state); if (entry == null) { break; } // 判斷連線是否過期,如過期則關閉並從可用連線集合中刪除 if (entry.isExpired(System.currentTimeMillis())) { entry.close(); } if (entry.isClosed()) { this.available.remove(entry); pool.free(entry, false); } else { break; } } // 如果從連線池中獲取到可用連線,更新可用連線和待釋放連線集合 if (entry != null) { this.available.remove(entry); this.leased.add(entry); onReuse(entry); return entry; } // 如果沒有可用連線,則建立新連線 final int maxPerRoute = getMax(route); // 建立新連線之前,檢查是否超過每個route連線池大小,如果超過,則刪除可用連線集合相應數量的連線(從總的可用連線集合和每個route的可用連線集合中刪除) final int excess = Math.max(0, pool.getAllocatedCount() + 1 - maxPerRoute); if (excess > 0) { for (int i = 0; i < excess; i++) { final E lastUsed = pool.getLastUsed(); if (lastUsed == null) { break; } lastUsed.close(); this.available.remove(lastUsed); pool.remove(lastUsed); } } if (pool.getAllocatedCount() < maxPerRoute) { //比較總的可用連線數量與總的可用連線集合大小,釋放多餘的連線資源 final int totalUsed = this.leased.size(); final int freeCapacity = Math.max(this.maxTotal - totalUsed, 0); if (freeCapacity > 0) { final int totalAvailable = this.available.size(); if (totalAvailable > freeCapacity - 1) { if (!this.available.isEmpty()) { final E lastUsed = this.available.removeLast(); lastUsed.close(); final RouteSpecificPool<T, C, E> otherpool = getPool(lastUsed.getRoute()); otherpool.remove(lastUsed); } } // 真正建立連線的地方 final C conn = this.connFactory.create(route); entry = pool.add(conn); this.leased.add(entry); return entry; } } //如果已經超過了每個route的連線池大小,則加入佇列等待有可用連線時被喚醒或直到某個終止時間 boolean success = false; try { if (future.isCancelled()) { throw new InterruptedException("Operation interrupted"); } pool.queue(future); this.pending.add(future); if (deadline != null) { success = this.condition.awaitUntil(deadline); } else { this.condition.await(); success = true; } if (future.isCancelled()) { throw new InterruptedException("Operation interrupted"); } } finally { //如果到了終止時間或有被喚醒時,則出隊,加入下次迴圈 pool.unqueue(future); this.pending.remove(future); } // 處理異常喚醒和超時情況 if (!success && (deadline != null && deadline.getTime() <= System.currentTimeMillis())) { break; } } throw new TimeoutException("Timeout waiting for connection"); } finally { this.lock.unlock(); } }
getPoolEntryBlocking方法用於獲取連線,主要有三步:
- 檢查可用連線集合中是否有可重複使用的連線,如果有則獲取連線,返回.
- 建立新連線,注意同時需要檢查可用連線集合(分為每個route的和全域性的)是否有多餘的連線資源,如果有,則需要釋放。
- 加入佇列等待;
從執行緒堆疊可以看出,第1個問題是由於走到了第3步。開始時是有時會報504異常,重新整理多次後會一直報504異常,經過跟蹤除錯發現前幾次會成功獲取到連線,而連線池滿後,後面的請求會阻塞。正常情況下當前面的連線釋放到連線池後,後面的請求會得到連線資源繼續執行,可現實是後面的連線一直處於等待狀態,猜想可能是由於連線一直未釋放導致。
我們來看一下連線在什麼時候會釋放。
RestTemplate
由於在調外部系統B時,使用的是RestTemplate的getForObject方法,從此入手跟蹤除錯看一看。
@Override
public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);
}
@Override
public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
HttpMessageConverterExtractor<T> responseExtractor =
new HttpMessageConverterExtractor<T>(responseType, getMessageConverters(), logger);
return execute(url, HttpMethod.GET, requestCallback, responseExtractor);
}
getForObject都呼叫了execute方法(其實RestTemplate的其它http請求方法呼叫的也是execute方法)
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {
URI expanded = getUriTemplateHandler().expand(url, uriVariables);
return doExecute(expanded, method, requestCallback, responseExtractor);
}
@Override
public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor, Map<String, ?> uriVariables) throws RestClientException {
URI expanded = getUriTemplateHandler().expand(url, uriVariables);
return doExecute(expanded, method, requestCallback, responseExtractor);
}
@Override
public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
return doExecute(url, method, requestCallback, responseExtractor);
}
所有execute方法都呼叫了同一個doExecute方法
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
ClientHttpResponse response = null;
try {
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
response = request.execute();
handleResponse(url, method, response);
if (responseExtractor != null) {
return responseExtractor.extractData(response);
}
else {
return null;
}
}
catch (IOException ex) {
String resource = url.toString();
String query = url.getRawQuery();
resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + resource + "\": " + ex.getMessage(), ex);
}
finally {
if (response != null) {
response.close();
}
}
}
doExecute方法建立了請求,然後執行,處理異常,最後關閉。可以看到關閉操作放在finally中,任何情況都會執行到,除非返回的response為null。
InterceptingClientHttpRequest
進入到request.execute()方法中,對應抽象類org.springframework.http.client.AbstractClientHttpRequest的execute方法
@Override
public final ClientHttpResponse execute() throws IOException {
assertNotExecuted();
ClientHttpResponse result = executeInternal(this.headers);
this.executed = true;
return result;
}
executeInternal方法是一個抽象方法,由子類實現(restTemplate內部的http呼叫實現方式有多種)。進入executeInternal方法,到達抽象類org.springframework.http.client.AbstractBufferingClientHttpRequest中
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() < 0) {
headers.setContentLength(bytes.length);
}
ClientHttpResponse result = executeInternal(headers, bytes);
this.bufferedOutput = null;
return result;
}
此抽象類在AbstractClientHttpRequest基礎之上添加了緩衝功能,可以儲存要傳送給伺服器的資料,然後一塊傳送。看這一句:
ClientHttpResponse result = executeInternal(headers, bytes);
也是一個executeInternal方法,不過引數不同,它也是一個抽象方法。進入方法,到達org.springframework.http.client.InterceptingClientHttpRequest類
protected final ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
InterceptingRequestExecution requestExecution = new InterceptingRequestExecution();
return requestExecution.execute(this, bufferedOutput);
}
例項化了一個帶攔截器的請求執行物件InterceptingRequestExecution,進入看一看。
public ClientHttpResponse execute(HttpRequest request, final byte[] body) throws IOException {
// 如果有攔截器,則執行攔截器並返回結果
if (this.iterator.hasNext()) {
ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
return nextInterceptor.intercept(request, body, this);
}
else {
// 如果沒有攔截器,則通過requestFactory建立request物件並執行
ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
delegate.getHeaders().add(entry.getKey(), value);
}
}
if (body.length > 0) {
if (delegate instanceof StreamingHttpOutputMessage) {
StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) delegate;
streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
@Override
public void writeTo(final OutputStream outputStream) throws IOException {
StreamUtils.copy(body, outputStream);
}
});
}
else {
StreamUtils.copy(body, delegate.getBody());
}
}
return delegate.execute();
}
}
看一下RestTemplate的配置:
RestTemplateBuilder builder = new RestTemplateBuilder();
return builder
.setConnectTimeout(customConfig.getRest().getConnectTimeOut())
.setReadTimeout(customConfig.getRest().getReadTimeout())
.interceptors(restTemplateLogInterceptor)
.errorHandler(new ThrowErrorHandler())
.build();
}
可以看到配置了連線超時,讀超時,攔截器,和錯誤處理器。
看一下攔截器的實現:
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
// 列印訪問前日誌
ClientHttpResponse execute = clientHttpRequestExecution.execute(httpRequest, bytes);
if (如果返回碼不是200) {
// 丟擲自定義執行時異常
}
// 列印訪問後日志
return execute;
}
可以看到當返回碼不是200時,丟擲異常。還記得RestTemplate中的doExecute方法吧,此處如果丟擲異常,雖然會執行doExecute方法中的finally程式碼,但由於返回的response為null(其實是有response的),沒有關閉response,所以這裡不能丟擲異常,如果確實想丟擲異常,可以在錯誤處理器errorHandler中丟擲,這樣確保response能正常返回和關閉。
RestTemplate原始碼部分解析
如何決定使用哪一個底層http框架
知道了原因,我們再來看一下RestTemplate在什麼時候決定使用什麼http框架。其實在通過RestTemplateBuilder例項化RestTemplate物件時就決定了。
看一下RestTemplateBuilder的build方法
public RestTemplate build() {
return build(RestTemplate.class);
}
public <T extends RestTemplate> T build(Class<T> restTemplateClass) {
return configure(BeanUtils.instantiate(restTemplateClass));
}
可以看到在例項化RestTemplate物件之後,進行配置。
public <T extends RestTemplate> T configure(T restTemplate) {
// 配置requestFactory
configureRequestFactory(restTemplate);
// 配置訊息轉換器
if (!CollectionUtils.isEmpty(this.messageConverters)) {
restTemplate.setMessageConverters(
new ArrayList<HttpMessageConverter<?>>(this.messageConverters));
}
//配置uri模板處理器
if (this.uriTemplateHandler != null) {
restTemplate.setUriTemplateHandler(this.uriTemplateHandler);
}
//配置錯誤處理器
if (this.errorHandler != null) {
restTemplate.setErrorHandler(this.errorHandler);
}
// 設定根路徑(一般為'/')
if (this.rootUri != null) {
RootUriTemplateHandler.addTo(restTemplate, this.rootUri);
}
// 配置登入驗證
if (this.basicAuthorization != null) {
restTemplate.getInterceptors().add(this.basicAuthorization);
}
//配置自定義restTemplate器
if (!CollectionUtils.isEmpty(this.restTemplateCustomizers)) {
for (RestTemplateCustomizer customizer : this.restTemplateCustomizers) {
customizer.customize(restTemplate);
}
}
//配置攔截器
restTemplate.getInterceptors().addAll(this.interceptors);
return restTemplate;
}
看一下方法的第一行,配置requestFactory。
private void configureRequestFactory(RestTemplate restTemplate) {
ClientHttpRequestFactory requestFactory = null;
if (this.requestFactory != null) {
requestFactory = this.requestFactory;
}
else if (this.detectRequestFactory) {
requestFactory = detectRequestFactory();
}
if (requestFactory != null) {
ClientHttpRequestFactory unwrappedRequestFactory = unwrapRequestFactoryIfNecessary(
requestFactory);
for (RequestFactoryCustomizer customizer : this.requestFactoryCustomizers) {
customizer.customize(unwrappedRequestFactory);
}
restTemplate.setRequestFactory(requestFactory);
}
}
可以指定requestFactory,也可以自動探測。看一下detectRequestFactory方法。
private ClientHttpRequestFactory detectRequestFactory() {
for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES
.entrySet()) {
ClassLoader classLoader = getClass().getClassLoader();
if (ClassUtils.isPresent(candidate.getKey(), classLoader)) {
Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(),
classLoader);
ClientHttpRequestFactory requestFactory = (ClientHttpRequestFactory) BeanUtils
.instantiate(factoryClass);
initializeIfNecessary(requestFactory);
return requestFactory;
}
}
return new SimpleClientHttpRequestFactory();
}
迴圈REQUEST_FACTORY_CANDIDATES集合,檢查classpath類路徑中是否存在相應的jar包,如果存在,則建立相應框架的封裝類物件。如果都不存在,則返回使用JDK方式實現的RequestFactory物件。
看一下REQUEST_FACTORY_CANDIDATES集合
private static final Map<String, String> REQUEST_FACTORY_CANDIDATES;
static {
Map<String, String> candidates = new LinkedHashMap<String, String>();
candidates.put("org.apache.http.client.HttpClient",
"org.springframework.http.client.HttpComponentsClientHttpRequestFactory");
candidates.put("okhttp3.OkHttpClient",
"org.springframework.http.client.OkHttp3ClientHttpRequestFactory");
candidates.put("com.squareup.okhttp.OkHttpClient",
"org.springframework.http.client.OkHttpClientHttpRequestFactory");
candidates.put("io.netty.channel.EventLoopGroup",
"org.springframework.http.client.Netty4ClientHttpRequestFactory");
REQUEST_FACTORY_CANDIDATES = Collections.unmodifiableMap(candidates);
}
可以看到共有四種Http呼叫實現方式,在配置RestTemplate時可指定,並在類路徑中提供相應的實現jar包。
Request攔截器的設計
再看一下InterceptingRequestExecution類的execute方法。
public ClientHttpResponse execute(HttpRequest request, final byte[] body) throws IOException {
// 如果有攔截器,則執行攔截器並返回結果
if (this.iterator.hasNext()) {
ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
return nextInterceptor.intercept(request, body, this);
}
else {
// 如果沒有攔截器,則通過requestFactory建立request物件並執行
ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
delegate.getHeaders().add(entry.getKey(), value);
}
}
if (body.length > 0) {
if (delegate instanceof StreamingHttpOutputMessage) {
StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) delegate;
streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
@Override
public void writeTo(final OutputStream outputStream) throws IOException {
StreamUtils.copy(body, outputStream);
}
});
}
else {
StreamUtils.copy(body, delegate.getBody());
}
}
return delegate.execute();
}
}
大家可能會有疑問,傳入的物件已經是request物件了,為什麼在沒有攔截器時還要再建立一遍request物件呢?
其實傳入的request物件在有攔截器的時候是InterceptingClientHttpRequest物件,沒有攔截器時,則直接是包裝了各個http呼叫實現框的Request。如HttpComponentsClientHttpRequest、OkHttp3ClientHttpRequest等。當有攔截器時,會執行攔截器,攔截器可以有多個,而這裡 this.iterator.hasNext() 不是一個迴圈,為什麼呢?祕密在於攔截器的intercept方法。
ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException;
此方法包含request,body,execution。exection型別為ClientHttpRequestExecution介面,上面的InterceptingRequestExecution便實現了此介面,這樣在呼叫攔截器時,傳入exection物件本身,然後再調一次execute方法,再判斷是否仍有攔截器,如果有,再執行下一個攔截器,將所有攔截器執行完後,再生成真正的request物件,執行http呼叫。
那如果沒有攔截器呢?
上面已經知道RestTemplate在例項化時會例項化RequestFactory,當發起http請求時,會執行restTemplate的doExecute方法,此方法中會建立Request,而createRequest方法中,首先會獲取RequestFactory
// org.springframework.http.client.support.HttpAccessor
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest request = getRequestFactory().createRequest(url, method);
if (logger.isDebugEnabled()) {
logger.debug("Created " + method.name() + " request for \"" + url + "\"");
}
return request;
}
// org.springframework.http.client.support.InterceptingHttpAccessor
public ClientHttpRequestFactory getRequestFactory() {
ClientHttpRequestFactory delegate = super.getRequestFactory();
if (!CollectionUtils.isEmpty(getInterceptors())) {
return new InterceptingClientHttpRequestFactory(delegate, getInterceptors());
}
else {
return delegate;
}
}
看一下RestTemplate與這兩個類的關係就知道呼叫關係了。
而在獲取到RequestFactory之後,判斷有沒有攔截器,如果有,則建立InterceptingClientHttpRequestFactory物件,而此RequestFactory在createRequest時,會建立InterceptingClientHttpRequest物件,這樣就可以先執行攔截器,最後執行建立真正的Request物件執行http呼叫。
結束語
- 在使用框架時,特別是在增強其功能,自定義行為時,要考慮到自定義行為對框架原有流程邏輯的影響,並且最好要熟悉框架相應功能的設計意圖。
- 在與外部事物互動,包括網路,磁碟,資料庫等,做到異常情況的處理,保證程式健壯性。