okhttp4.11源码分析

目录

一,OKHTTP时序图

二,OKHTTP类图

三,OKHTTP流程图


一,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更快一些,还有就是刚才说的常量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值