目录
一,OKHTTP时序图
上图是整个okhttp一次完整的请求过程,时序图里面有些部分为了方便采用了简单的描述,描述了主要的流程,细节的话,可以具体参考这个流程图看代码
二,OKHTTP类图
上述类图列举出了okhttp最重要的核心类成员
三,OKHTTP流程图
3.1 上图详细的列举出来了okhttp加载网络请求的详细流程,对于intercepter这块,重点的说下,这本身是一个责任链模式,在intercepter里面持有chain对象,每次执行intercepter的时候,都会创建新的RealInterceptorChain对象,在RealInterceptorChain对象里面报错了所有的intercepter,创建新的RealInterceptorChain时候会把上个intercepter相关的数据都会传到RealInterceptorChain,所以这个时候在新的intercepter里面,就会有上个intercepter传递过来的和请求相关的所有数据,依次类推
3.2 对于上文提到的同一个主机最多的连接数是5个,是因为连接池最大的空闲连接数是5个
class ConnectionPool internal constructor(
internal val delegate: RealConnectionPool
) {
constructor(
maxIdleConnections: Int,
keepAliveDuration: Long,
timeUnit: TimeUnit
) : this(RealConnectionPool(
taskRunner = TaskRunner.INSTANCE,
maxIdleConnections = maxIdleConnections,
keepAliveDuration = keepAliveDuration,
timeUnit = timeUnit
))
constructor() : this(5, 5, TimeUnit.MINUTES)
class ConnectionPool internal constructor(
internal val delegate: RealConnectionPool
) {
constructor(
maxIdleConnections: Int,
keepAliveDuration: Long,
timeUnit: TimeUnit
) : this(RealConnectionPool(
taskRunner = TaskRunner.INSTANCE,
maxIdleConnections = maxIdleConnections,
keepAliveDuration = keepAliveDuration,
timeUnit = timeUnit
))
最关键的就是this(5, 5, TimeUnit.MINUTES)这话,这也就是if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue 的缘故,但是这么写的话,觉得okhttp这块写的就不是很好,应该使用一个公共的常量,那么多个地方使用的话,都是用这一个常量,因为使用魔法数字很容易出错
3.3,其实阅读OKHTTP源码发现里面还是有一些小点可以优化的,比如创建Chain的时候应该使用原型模式,clone效率会更高一些, 比去new更快一些,还有就是刚才说的常量