在上一篇文章里我们介绍了 httpclient 连接池中连接的可用性检查,在这里我们主要介绍空闲 http 连接的清理。对于连接池中的连接基本都是复用的,其中避免不了 server 端主动关闭连接,这个时候取出的连接自然是不可用的,当然可以通过上一篇文章中的可用性检查避免。但同时 httpclient 连接池也提供了 http 连接的清理策略,用来对连接进行清除。
http 连接的清理主要涉及了以下几个关键点:
如何开启连接清理
连接池中空闲连接的清理由 HttpClientBuilder 的 evictIdleConnections(ildleTime, timeUnit) 方法和 evictExpiredConnections() 方法进行设置。在进行 build 的时候根据上述设置开启清理,核心代码如下:
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();
}
如何进行连接清理
由上面 IdleConnectionEvictor 的代码可知,清理的核心是运行PoolingHttpClientConnectionManager 的 closeExpiredConnections()/closeIdleConnections() 这两个方法,而这两个方法本质是则是调用 Cpool 对象实例的 closeIdle() 方法和 closeExpired() 方法,核心代码如下:
public void closeIdle(final long idletime, final TimeUnit timeUnit) {
Args.notNull(timeUnit, "Time unit");
long time = timeUnit.toMillis(idletime);
if (time < 0) {
time = 0;
}
final long deadline = System.currentTimeMillis() - time;
enumAvailable(new PoolEntryCallback<T, C>() {
@Override
public void process(final PoolEntry<T, C> entry) {
if (entry.getUpdated() <= deadline) {
entry.close();
}
}
});
}
public void closeExpired() {
final long now = System.currentTimeMillis();
enumAvailable(new PoolEntryCallback<T, C>() {
@Override
public void process(final PoolEntry<T, C> entry) {
if (entry.isExpired(now)) {
entry.close();
}
}
});
}
protected void enumAvailable(final PoolEntryCallback<T, C> callback) {
this.lock.lock();
try {
final Iterator<E> it = this.available.iterator();
while (it.hasNext()) {
final E entry = it.next();
callback.process(entry);
if (entry.isClosed()) {
final RouteSpecificPool<T, C, E> pool = getPool(entry.getRoute());
pool.remove(entry);
it.remove();
}
}
purgePoolMap();
} finally {
this.lock.unlock();
}
}
目前先写到这里,下一篇我们开始介绍 httpclient 连接池请求的 retry 和 ssl 的支持。