OKHttp的复用连接池
为了解决TCP握手和挥手的效率问题,HTTP有一种叫做keepalive connections的机制,而OKHttp支持5个并发socket连接,默认keepAlive时间为5分钟,接下来看看OKHttp是怎么复用连接的
1. 主要变量与构造方法
连接池的类位于ConnectionPool,他的主要变量及作用如下:
//线程池
private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));
/** The maximum number of idle connections for each address. */
//最大空闲连接数
private final int maxIdleConnections;
//连接时间
private final long keepAliveDurationNs;
//回收空闲连接的runnable
private final Runnable cleanupRunnable = new Runnable() {
···};
//双向队列,里面维护了RealConnection也就是socket物理连接的包装
private final Deque<RealConnection> connections = new ArrayDeque<>();
//记录连接失败的路线名单,当连接失败就会把失败的线路加进去
final RouteDatabase routeDatabase = new RouteDatabase();
boolean cleanupRunning;
构造方法
public ConnectionPool() {
this(5, 5, TimeUnit.MINUTES);
}
public ConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
this.maxIdleConnections = maxIdleConnections;
this.keepAliveDurationNs = timeUnit.toNanos(keepAliveDuration);
// Put a floor on the keep alive duration, otherwise cleanup will spin loop.
if (keepAliveDuration <= 0) {
throw new IllegalArgumentException("keepAliveDuration <= 0: " + keepAliveDuration);
}
}
默认socket最大连接数为5个,连接时间为5分钟。ConnectionPool实例是在OKHttpClient实例化是创建的。
2. 缓存操作
ConnectionPool对Deque <RealConnection>
进行操作的方法分别是put、get、connectionBecameIdle和evictAll这几个操作,分别对应放