okhttp之StreamAllocation

转载请以链接形式标明出处:
本文出自:103style的博客


base on 3.12.0


目录

  • 背景
  • 简介
  • StreamAllocation 的成员变量
  • StreamAllocation 的构造函数
  • StreamAllocation 的相关方法
  • 小结

背景

HTTP 的版本从最初的 1.0版本,到后续的 1.1版本,再到后续的 google 推出的SPDY,后来再推出 2.0版本,HTTP协议越来越完善。okhttp也是根据2.0和1.1/1.0作为区分,实现了两种连接机制.

http2.0解决了老版本(1.1和1.0)最重要两个问题:

http2.0 使用 多路复用 的技术,多个 stream 可以共用一个 socket 连接。每个 tcp连接都是通过一个 socket 来完成的,socket 对应一个 hostport,如果有多个stream(即多个 Request) 都是连接在一个 hostport上,那么它们就可以共同使用同一个 socket ,这样做的好处就是 可以减少TCP的一个三次握手的时间
OKHttp里面,负责连接的是 RealConnection


简介

官方注释是 StreamAllocation是用来协调ConnectionsStreamsCalls这三个实体的。

HTTP通信 执行 网络请求Call 需要在 连接Connection 上建立一个新的 Stream,我们将 StreamAllocation 称之 的桥梁,它负责为一次 请求 寻找 连接 并建立 ,从而完成远程通信。

然后我们先来看看 StreamAllocation 这个类是在什么地方初始化的,以及在哪些地方用到?

选中StreamAllocation 的构造方法,在 AndroidStudio 中按 Alt + F7,我们发现是在 RetryAndFollowUpInterceptor这个拦截器intercept(Chain chain)中创建的.
然后往下层拦截器传递,直到 ConnectInterceptor 以及 CallServerInterceptor才继续用到。

public final class RetryAndFollowUpInterceptor implements Interceptor {
    ...
  @Override public Response intercept(Chain chain) throws IOException {
    ...
    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
    ...
}
public final class ConnectInterceptor implements Interceptor {
  ...
  @Override public Response intercept(Chain chain) throws IOException {
    ...
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();
    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }
}
public final class CallServerInterceptor implements Interceptor {
  ...
  @Override public Response intercept(Chain chain) throws IOException {
    ...
        streamAllocation.noNewStreams();
    ...
  }
 ...
}

StreamAllocation 的成员变量

  • 由构造方法中传入的变量:
    • public final Address address; 地址
    • private final ConnectionPool connectionPool; 连接池
    • public final Call call; 请求对象
    • public final EventListener eventListener; 事件回调
    • private final Object callStackTrace; 日志
    • private final RouteSelector routeSelector; 路由选择器
  • private RouteSelector.Selection routeSelection; 选中的路由集合
  • private Route route; 路由
  • private RealConnection connection; HTTP连接
  • private HttpCodec codec; HTTP请求的编码和响应的解码

StreamAllocation 的构造函数

RetryAndFollowUpInterceptor 中传入了 :

public StreamAllocation(ConnectionPool connectionPool, Address address, Call call,
                        EventListener eventListener, Object callStackTrace) {
    this.connectionPool = connectionPool;
    this.address = address;
    this.call = call;
    this.eventListener = eventListener;
    this.routeSelector = new RouteSelector(address, routeDatabase(), call, eventListener);
    this.callStackTrace = callStackTrace;
}

StreamAllocation 的相关方法

我们在简介中介绍 StreamAllocation 在哪里创建的时候,发现拦截器中主要调用的就是 newStream(...)noNewStreams() 这两个方法。那我们先来看看这两个方法吧。

  • newStream(...)
    主要就是获取一个 可用的连接 和 对应连接协议的编解码实例,并赋值给变量 connectioncodec.
    public HttpCodec newStream(...) {
      ...
      try {
        //在连接池中找到一个可用的连接  没有则创建一个
        RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
            writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
        //获取对应协议的 编解码类 Http1Codec or Http2Codec
        HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);
        synchronized (connectionPool) {
          codec = resultCodec;
          return resultCodec;
        }
      } catch (IOException e) {
        throw new RouteException(e);
      }
    }
    
  • noNewStreams()
    主要就是设置当前的 connection 不能再创建新的流。
    public void noNewStreams() {
      Socket socket;
      Connection releasedConnection;
      synchronized (connectionPool) {
        releasedConnection = connection;
        socket = deallocate(true, false, false);
        if (connection != null) releasedConnection = null;
      }
      closeQuietly(socket);
      if (releasedConnection != null) {
        eventListener.connectionReleased(call, releasedConnection);
      }
    }
    

继续看下 newStream(...) 获取可用连接的流程。

  • findHealthyConnection(...)
    通过findConnection(...)得到一个连接,如果是新创建的连接,则直接返回,否则检查 连接 是否已经可以开始承载新的流,不行则继续findConnection(...).

    private RealConnection findHealthyConnection(...) throws IOException {
      while (true) {
        RealConnection candidate = findConnection(...);
        //如果是一个新创建的连接 则直接返回
        synchronized (connectionPool) {
          if (candidate.successCount == 0) {
            return candidate;
          }
        }
        //否则检查 连接 是否已经可以开始承载新的流
        if (!candidate.isHealthy(doExtensiveHealthChecks)) {
          noNewStreams();
          continue;
        }
        return candidate;
      }
    }
    
  • findConnection(...)

    • 1.0 第一个 synchronized (connectionPool) 这一段首先尝试使用当前的变量connection. 如果当前的connectionnull, 则通过Internal.instance.get(connectionPool, address, this, null);连接池 中获取对应 address 的连接 赋值给 connection,如果当前的 connection不为null,则直接返回.
    • 2.0 如果上一步没有找到可用连接,则看是否有其他可用路由。
    • 3.0 第二个 synchronized (connectionPool) 这一段,3.1如果有其他路由则先去连接池查询看是否有对应连接, 3.2没有的话则创建一个新的 RealConnection,并赋值给变量 connection. 3.3在连接池中找到的话则直接返回。
    • 4.0 然后新创建的连接开始握手连接,然后放入连接池,然后返回。
    private RealConnection findConnection(...) throws IOException {
      ...
      //1.0 尝试使用当前的 connection,或者查找 连接池
      synchronized (connectionPool) {
        ...
        releasedConnection = this.connection;
        if (this.connection != null) {
          result = this.connection;
          releasedConnection = null;
        }
        if (!reportedAcquired) {
          releasedConnection = null;
        }
        if (result == null) {
          Internal.instance.get(connectionPool, address, this, null);
          if (connection != null) {
            foundPooledConnection = true;
            result = connection;
          } else {
            selectedRoute = route;
          }
        }
      }
      ...
      if (result != null) {
        return result;
      }
    
      //2.0 看是否有其他的路由
      boolean newRouteSelection = false;
      if (selectedRoute == null && (routeSelection == null || !routeSelection.hasNext())) {
        newRouteSelection = true;
        routeSelection = routeSelector.next();
      }
      //3.0 
      synchronized (connectionPool) {
        if (newRouteSelection) {
          //3.1 有其他路由则先去连接池查询看是否有对应连接
        }
        if (!foundPooledConnection) {
          ...
          //3.2 没有的话则创建一个新的RealConnection,并赋值给变量 connection
          result = new RealConnection(connectionPool, selectedRoute);
          acquire(result, false);
        }
      }
      // 3.3 在连接池中找到的话则直接返回
      if (foundPooledConnection) {
        eventListener.connectionAcquired(call, result);
        return result;
      }
      //4.0 新创建的连接开始握手连接
      result.connect(...);
      synchronized (connectionPool) {
        reportedAcquired = true;
        Internal.instance.put(connectionPool, result);
        ...
      }
      ...
      return result;
    }
    

    流程图大概如下:


    okhttp之StreamAllocation.findHealthyConnection(...)
  • acquire(...)从连接池找到对应连接 赋值给StreamAllocation

    public void acquire(RealConnection connection, boolean reportedAcquired) {
      assert (Thread.holdsLock(connectionPool));
      if (this.connection != null) throw new IllegalStateException();
      this.connection = connection;
      this.reportedAcquired = reportedAcquired;
      connection.allocations.add(new StreamAllocationReference(this, callStackTrace));
    }
    
  • 获取成员变量的一些方法.

    public HttpCodec codec() {
      synchronized (connectionPool) {
        return codec;
      }
    }
    public Route route() {
      return route;
    }
    public synchronized RealConnection connection() {
      return connection;
    }
    
  • release() 资源释放

    public void release() {
      Socket socket;
      Connection releasedConnection;
      synchronized (connectionPool) {
        releasedConnection = connection;
        socket = deallocate(false, true, false);
        if (connection != null) releasedConnection = null;
      }
      closeQuietly(socket);
      if (releasedConnection != null) {
        Internal.instance.timeoutExit(call, null);
        eventListener.connectionReleased(call, releasedConnection);
        eventListener.callEnd(call);
      }
    }
    

小结

  • 介绍了HTTP2HTTP1 的区别,HTTP2使用 多路复用 的技术,减少了同地址的TCP握手时间。

  • 介绍了 StreamAllocation 的主要方法newStream(...),以及其中获取可用 Connection 的具体逻辑.

  • newStream(...) 返回的 HttpCodec 这个 编解码的示例后面也会介绍。


参考文章

如果觉得不错的话,请帮忙点个赞呗。

以上


扫描下面的二维码,关注我的公众号 Android1024, 点关注,不迷路。

Android1024

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容

  • https://blog.csdn.net/joye123/article/details/82115562?ut...
    kkgo阅读 4,406评论 0 0
  • 因为项目集成,在使用Fresco的时候,有集成OkHttp,所以接下来是OkHttp3.0的 简单一个列子,其中里...
    TragedyGo阅读 1,354评论 0 1
  • 晚上下班的时候,和她一起,两个人骑行,在一条路上,她在前面,我跟在后面。我慢慢地蹬着车,追着地上路灯下她的...
    落七画阅读 408评论 5 1
  • 我不得不把这三者写到一起,因为在我这个伪重庆人心中,它们之间口味的区别:不存在(búcúnzāi,请跟着拼音学习重...
    令阿玲阿玲阅读 328评论 0 0
  • 擦窗户 有一份愉快 叫做透亮 有一点嘚瑟 邻居更懒 有一分惬意 泡茶自赏 有一种舒畅 净澈吾窗
    愚壹阅读 230评论 0 0