一次响应的过程
在高并发的请求连接情况下或者同个客户端多次频繁的请求操作,无限制的创建会导致性能低下。
如果使用keep-alive
在timeout空闲时间内,连接不会关闭,相同重复的request将复用原先的connection,减少握手的次数,大幅提高效率。
并非keep-alive的timeout设置时间越长,就越能提升性能。长久不关闭会造成过多的僵尸连接和泄露连接出现。
那么okttp在客户端是如果类似于客户端做到的keep-alive的机制。
2、连接池的使用
连接池的类位于okhttp3.ConnectionPool。我们的主旨是了解到如何在timeout时间内复用connection,并且有效的对其进行回收清理操作。
其成员变量代码片
/**
- Background threads are used to cleanup expired connections. There will be at most a single
- thread running per connection pool. The thread pool executor permits the pool itself to be
- garbage collected.
/
private static final Executor executor = new ThreadPoolExecutor(0 / corePoolSize /,
Integer.MAX_VALUE / maximumPoolSize /, 60L / keepAliveTime */, TimeUnit.SECONDS,
new SynchronousQueue(), Util.threadFactory(“OkHttp ConnectionPool”, true));
/** The maximum number of idle connections for each address. */
private final int maxIdleConnections;
private final Deque connecti