本文只是简单分析了httpclient4.5版本,从连接池里请求一个连接时候的实现流程和源码分析,下面是流程图:
注意其中的大连接池和小连接池的区别,大连接池管理所有连接信息,包含每个路由对应的连接信息,小连接池管理每个路由对应的连接信息。
流程图
p.s 流程图的每一步并不是完全按照代码的每一步进行说明的,是按照代码的整体流程说明,并没有精细到每一行代码。
关键源码
下面的代码我加了注释,在类:org.apache.http.pool.AbstractConnPool里,主要是连接获取计算部分的代码
private E getPoolEntryBlocking(
final T route, final Object state,
final long timeout, final TimeUnit tunit,
final PoolEntryFuture<E> future)
throws IOException, InterruptedException, TimeoutException {
Date deadline = null;
if (timeout > 0) {
// 设置超时日期
deadline = new Date
(System.currentTimeMillis() + tunit.toMillis(timeout));
}
this.lock.lock();
try {
// 根据路由信息获取该路由的小连接池,没有则创建,有则从缓存取出
final RouteSpecificPool<T, C, E> pool = getPool(route);
E entry = null;
while (entry == null) {
Asserts.check(!this.isShutDown, "Connection pool shut down");
for (;;) {
// 根据连接状态(用户权限、令牌等)获取连接信息
entry = pool.getFree(state);
if (entry == null) {
break;
}
// 下面是确定连接有效(未过期,未关闭)
if (entry.isExpired(System.currentTimeMillis())) {
entry.close();
} else if (this.validateAfterInactivity > 0) {
if (entry.getUpdated() + this.validateAfterInactivity <= System.currentTimeMillis()) {
if (!validate(entry)) {
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;
}
// New connection is needed
final int maxPerRoute = getMax(route);
// Shrink the pool prior to allocating a new connection
// 计算路由池创建的总连接数(可用+在用)是否达到了路由最大连接数
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);
}
}
// 这时候路由池里总连接数小于路由最大连接数(相等的话,不是移除了1个么)
// ,并且还有可用容量的话(大连接池内的总连接数可用连接还有配额),就新建一个连接
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;
}
}
// 走到这里说明无可用连接,总连接数満了,或者达到了路由最大连接数,
// 这里候线程挂起,如果配置的有超时,等待超时唤醒,或者正常唤醒,然后继续下轮连接获取
// 连接释放连接回连接池的时候,会唤醒这些阻塞线程,否则就是超时了或者出现中断
boolean success = false;
try {
pool.queue(future);
this.pending.add(future);
success = future.await(deadline);
} finally {
// In case of 'success', we were woken up by the
// connection pool and should now have a connection
// waiting for us, or else we're shutting down.
// Just continue in the loop, both cases are checked.
pool.unqueue(future);
this.pending.remove(future);
}
// check for spurious wakeup vs. timeout
if (!success && (deadline != null) &&
(deadline.getTime() <= System.currentTimeMillis())) {
break;
}
}
throw new TimeoutException("Timeout waiting for connection");
} finally {
this.lock.unlock();
}
}