• 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个

    1. class ConnectionPool internal constructor(
    2. internal val delegate: RealConnectionPool
    3. ) {
    4. constructor(
    5. maxIdleConnections: Int,
    6. keepAliveDuration: Long,
    7. timeUnit: TimeUnit
    8. ) : this(RealConnectionPool(
    9. taskRunner = TaskRunner.INSTANCE,
    10. maxIdleConnections = maxIdleConnections,
    11. keepAliveDuration = keepAliveDuration,
    12. timeUnit = timeUnit
    13. ))
    14. constructor() : this(5, 5, TimeUnit.MINUTES)
    1. class ConnectionPool internal constructor(
    2. internal val delegate: RealConnectionPool
    3. ) {
    4. constructor(
    5. maxIdleConnections: Int,
    6. keepAliveDuration: Long,
    7. timeUnit: TimeUnit
    8. ) : this(RealConnectionPool(
    9. taskRunner = TaskRunner.INSTANCE,
    10. maxIdleConnections = maxIdleConnections,
    11. keepAliveDuration = keepAliveDuration,
    12. timeUnit = timeUnit
    13. ))

    最关键的就是this(5, 5, TimeUnit.MINUTES)这话,这也就是if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue 的缘故,但是这么写的话,觉得okhttp这块写的就不是很好,应该使用一个公共的常量,那么多个地方使用的话,都是用这一个常量,因为使用魔法数字很容易出错

    3.3,其实阅读OKHTTP源码发现里面还是有一些小点可以优化的,比如创建Chain的时候应该使用原型模式,clone效率会更高一些, 比去new更快一些,还有就是刚才说的常量

  • 相关阅读:
    网页【CSS】滚动条
    MySQL数据库简介+库表管理操作+数据库用户管理
    《C++ Primer》第9章 顺序容器(二)
    机器学习AI大模型的开源与闭源:哪个更好?
    通过Moonbeam路由流动性,如何转移token至Hydra?
    抽丝剥茧,Redis使用事件总线EventBus或AOP优化健康检测
    Kleopatra与MinGW64中gpg冲突
    蓝桥杯:模拟、枚举
    mybatis plus框架的@TableField注解不生效问题总结
    opencv快速入门(三)——图像几何变换
  • 原文地址:https://blog.csdn.net/qq_18757557/article/details/133683835