探索HttpClient中的close方法及其對(duì)連接的影響
序
本文主要研究一下HttpClient的close
CloseableHttpClient
org/apache/http/impl/client/CloseableHttpClient.java
@Contract(threading = ThreadingBehavior.SAFE)
public abstract class CloseableHttpClient implements HttpClient, Closeable {
@Override
public <T> T execute(final HttpHost target, final HttpRequest request,
final ResponseHandler<? extends T> responseHandler, final HttpContext context)
throws IOException, ClientProtocolException {
Args.notNull(responseHandler, "Response handler");
final CloseableHttpResponse response = execute(target, request, context);
try {
final T result = responseHandler.handleResponse(response);
final HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
return result;
} catch (final ClientProtocolException t) {
// Try to salvage the underlying connection in case of a protocol exception
final HttpEntity entity = response.getEntity();
try {
EntityUtils.consume(entity);
} catch (final Exception t2) {
// Log this exception. The original exception is more
// important and will be thrown to the caller.
this.log.warn("Error consuming content after an exception.", t2);
}
throw t;
} finally {
response.close();
}
}
//......
}CloseableHttpClient聲明實(shí)現(xiàn)HttpClient, Closeable接口
InternalHttpClient
org/apache/http/impl/client/InternalHttpClient.java
@Contract(threading = ThreadingBehavior.SAFE_CONDITIONAL)
@SuppressWarnings("deprecation")
class InternalHttpClient extends CloseableHttpClient implements Configurable {
private final Log log = LogFactory.getLog(getClass());
private final ClientExecChain execChain;
private final HttpClientConnectionManager connManager;
private final HttpRoutePlanner routePlanner;
private final Lookup<CookieSpecProvider> cookieSpecRegistry;
private final Lookup<AuthSchemeProvider> authSchemeRegistry;
private final CookieStore cookieStore;
private final CredentialsProvider credentialsProvider;
private final RequestConfig defaultConfig;
private final List<Closeable> closeables;
public InternalHttpClient(
final ClientExecChain execChain,
final HttpClientConnectionManager connManager,
final HttpRoutePlanner routePlanner,
final Lookup<CookieSpecProvider> cookieSpecRegistry,
final Lookup<AuthSchemeProvider> authSchemeRegistry,
final CookieStore cookieStore,
final CredentialsProvider credentialsProvider,
final RequestConfig defaultConfig,
final List<Closeable> closeables) {
super();
Args.notNull(execChain, "HTTP client exec chain");
Args.notNull(connManager, "HTTP connection manager");
Args.notNull(routePlanner, "HTTP route planner");
this.execChain = execChain;
this.connManager = connManager;
this.routePlanner = routePlanner;
this.cookieSpecRegistry = cookieSpecRegistry;
this.authSchemeRegistry = authSchemeRegistry;
this.cookieStore = cookieStore;
this.credentialsProvider = credentialsProvider;
this.defaultConfig = defaultConfig;
this.closeables = closeables;
}
//......
@Override
public void close() {
if (this.closeables != null) {
for (final Closeable closeable: this.closeables) {
try {
closeable.close();
} catch (final IOException ex) {
this.log.error(ex.getMessage(), ex);
}
}
}
}
}InternalHttpClient繼承了CloseableHttpClient,其構(gòu)造器要求傳入closeables,它實(shí)現(xiàn)了close方法,它主要是遍歷closeables,挨個(gè)執(zhí)行close
HttpClientBuilder
org/apache/http/impl/client/HttpClientBuilder.java
public class HttpClientBuilder {
private List<Closeable> closeables;
private boolean connManagerShared;
//......
/**
* For internal use.
*/
protected void addCloseable(final Closeable closeable) {
if (closeable == null) {
return;
}
if (closeables == null) {
closeables = new ArrayList<Closeable>();
}
closeables.add(closeable);
}
public CloseableHttpClient build() {
//......
List<Closeable> closeablesCopy = closeables != null ? new ArrayList<Closeable>(closeables) : null;
if (!this.connManagerShared) {
if (closeablesCopy == null) {
closeablesCopy = new ArrayList<Closeable>(1);
}
final HttpClientConnectionManager cm = connManagerCopy;
if (evictExpiredConnections || evictIdleConnections) {
final IdleConnectionEvictor connectionEvictor = new IdleConnectionEvictor(cm,
maxIdleTime > 0 ? maxIdleTime : 10, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS,
maxIdleTime, maxIdleTimeUnit);
closeablesCopy.add(new Closeable() {
@Override
public void close() throws IOException {
connectionEvictor.shutdown();
try {
connectionEvictor.awaitTermination(1L, TimeUnit.SECONDS);
} catch (final InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
}
});
connectionEvictor.start();
}
closeablesCopy.add(new Closeable() {
@Override
public void close() throws IOException {
cm.shutdown();
}
});
}
//......
return new InternalHttpClient(
execChain,
connManagerCopy,
routePlannerCopy,
cookieSpecRegistryCopy,
authSchemeRegistryCopy,
defaultCookieStore,
defaultCredentialsProvider,
defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT,
closeablesCopy);
}
}HttpClientBuilder定義了addCloseable方法用于添加closeable,不過(guò)是protected;而build方法在connManagerShared參數(shù)為false的時(shí)候(默認(rèn))會(huì)創(chuàng)建closeablesCopy,創(chuàng)建Closeable去關(guān)閉HttpClientConnectionManager并添加到closeablesCopy中;
在開(kāi)啟evictExpiredConnections或者evictIdleConnections的時(shí)候會(huì)創(chuàng)建IdleConnectionEvictor,然后創(chuàng)建關(guān)閉connectionEvictor的Closeable添加到closeablesCopy中
最后將這些closeablesCopy傳遞給InternalHttpClient的構(gòu)造器
小結(jié)
HttpClient(CloseableHttpClient)的close方法會(huì)關(guān)閉一系列的Closeable,這些Closeable在HttpClientBuilder的build方法會(huì)構(gòu)建好然后傳遞給InternalHttpClient;默認(rèn)情況下這些closeable包括HttpClientConnectionManager的關(guān)閉、IdleConnectionEvictor的關(guān)閉。
以上就是探索HttpClient中的close方法及其對(duì)連接的影響的詳細(xì)內(nèi)容,更多關(guān)于HttpClient close方法的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- httpclient connect連接請(qǐng)求方法源碼解讀
- httpclient getPoolEntryBlocking連接池方法源碼解讀
- httpclient staleConnectionCheckEnabled獲取連接流程解析
- 解讀httpclient的validateAfterInactivity連接池狀態(tài)檢測(cè)
- httpclient的disableConnectionState方法工作流程
- HttpClient的RedirectStrategy重定向處理核心機(jī)制
- HttpClient HttpRoutePlanner接口確定請(qǐng)求目標(biāo)路由
- httpclient ConnectionHolder連接池連接保持源碼解析
相關(guān)文章
Java中如何利用Set判斷List集合中是否有重復(fù)元素
在開(kāi)發(fā)工作中,我們有時(shí)需要去判斷List集合中是否含有重復(fù)的元素,這時(shí)候我們不需要找出重復(fù)的元素,我們只需要返回一個(gè)?Boolean?類(lèi)型就可以了,下面通過(guò)本文給大家介紹Java中利用Set判斷List集合中是否有重復(fù)元素,需要的朋友可以參考下2023-05-05
Java基于rest assured實(shí)現(xiàn)接口測(cè)試過(guò)程解析
這篇文章主要介紹了Java基于rest assured實(shí)現(xiàn)接口測(cè)試過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
@Transactional跟@DS動(dòng)態(tài)數(shù)據(jù)源注解沖突的解決
這篇文章主要介紹了@Transactional跟@DS動(dòng)態(tài)數(shù)據(jù)源注解沖突的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Java DriverManager.getConnection()獲取數(shù)據(jù)庫(kù)連接
這篇文章主要介紹了Java DriverManager.getConnection()獲取數(shù)據(jù)庫(kù)連接,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
springboot搭建訪客管理系統(tǒng)的實(shí)現(xiàn)示例
這篇文章主要介紹了springboot搭建訪客管理系統(tǒng)的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
SpringBoot統(tǒng)計(jì)接口調(diào)用耗時(shí)的三種方式
在實(shí)際開(kāi)發(fā)中,了解項(xiàng)目中接口的響應(yīng)時(shí)間是必不可少的事情,SpringBoot 項(xiàng)目支持監(jiān)聽(tīng)接口的功能也不止一個(gè),接下來(lái)我們分別以 AOP、ApplicationListener、Tomcat 三個(gè)方面去實(shí)現(xiàn)三種不同的監(jiān)聽(tīng)接口響應(yīng)時(shí)間的操作,需要的朋友可以參考下2024-06-06
Springboot集成JWT實(shí)現(xiàn)登錄注冊(cè)的示例代碼
本文主要介紹了Springboot集成JWT實(shí)現(xiàn)登錄注冊(cè)的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06
Java中NullPointerException的異常解決
本文解釋了Java中的NullPointerException是如何產(chǎn)生的,及使用Optional和Objects.requireNonNull()來(lái)避免此類(lèi)異常的方法,感興趣的可以了解一下2025-12-12
SpringBoot集成validation校驗(yàn)參數(shù)遇到的坑
這篇文章主要介紹了SpringBoot集成validation校驗(yàn)參數(shù)遇到的坑,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
Java中的Semaphore信號(hào)量簡(jiǎn)析
這篇文章主要介紹了Java中的Semaphore信號(hào)量簡(jiǎn)析,Semaphore:信號(hào)量,用來(lái)限制能同時(shí)訪問(wèn)共享資源的線程上限,使用Semaphore實(shí)現(xiàn)簡(jiǎn)單連接池,對(duì)比享元模式下的實(shí)現(xiàn)(用wait和notify),性能和可讀性要更好,需要的朋友可以參考下2023-12-12

