美文网首页
okhttp 3.10连接复用原理

okhttp 3.10连接复用原理

作者: 展翅而飞 | 来源:发表于2018-07-06 14:57 被阅读0次

    主文okhttp3.10介绍okhttp的连接复用。

    Keep-Alive机制:当一个http请求完成后,tcp连接不会立即释放,如果有新的http请求,并且host和上次一样,那么可以复用tcp连接,省去重新连接的过程。

    如果没有开启Keep-Alive,一个http请求就需要一次tcp连接,非常浪费资源。我们来看okhttp与连接相关的四个类,重点看连接的管理。

    • Collection
    • HttpCodec
    • StreamAllocation
    • ConnectionPool

    连接和流

    public interface Connection {
      Route route();
      Socket socket();
      @Nullable Handshake handshake();
      Protocol protocol();
    }
    

    Connection描述http的物理连接,封装了Socket,具体的实现类是RealConnection,其他三个变量Route、Handshake、Protocol是http协议相关类。(只要知道Connection是请求发送和响应的通道,真系要进入http原理时再讲)


    public interface HttpCodec {
      Sink createRequestBody(Request request, long contentLength);
      void writeRequestHeaders(Request request) throws IOException;
      void flushRequest() throws IOException;
      void finishRequest() throws IOException;
      Response.Builder readResponseHeaders(boolean expectContinue) throws IOException;
      ResponseBody openResponseBody(Response response) throws IOException;
      void cancel();
    }
    

    HttpCodec里是一些read、write方法,使用了okio,它是一个比java.io更高效的库(具体原理先book定下一篇讲)。Source和Sink,分别对应java.io的InputStream和OutputStream,就是输入输出。

    http1和http2有不同的实现,http2是未来,看Http1Codec的。


    在http1.1,一个连接只能有一个流,而在http2则可以支持多个流。为了管理一个连接上的多个流,okhttp使用StreamAllocation作为连接和流的桥梁。在RealConnection中保存了StreamAllocationd的一个列表,作为连接上流的计数器。如果列表大小为0,表示连接是空闲的,可以回收;否则连接还在用,不能关闭。

    public final List<Reference<StreamAllocation>> allocations = new ArrayList<>();
    

    操作allocations对应的增减方法是aquire和release:

    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));
    }
    

    为连接新增一个流,StreamAllocation用弱引用包装为StreamAllocationReference,直接加入allocations。

    释放StreamAllocation管理的流的方法有两个,一个供外部调用,public、没入参的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) {
        eventListener.connectionReleased(call, releasedConnection);
      }
    }
    

    最重要是调用deallocate,为什么返回socket并尝试执行关闭呢?连接上可能有多个流喔!可以猜想到deallocate肯定操作减少allocations,当allocations空了,返回连接的socket关闭。

    private Socket deallocate(boolean noNewStreams, boolean released, boolean streamFinished) {
      assert (Thread.holdsLock(connectionPool));
    
      if (streamFinished) {
        this.codec = null;
      }
      if (released) {
        this.released = true;
      }
      Socket socket = null;
      if (connection != null) {
        if (noNewStreams) {
          connection.noNewStreams = true;
        }
        if (this.codec == null && (this.released || connection.noNewStreams)) {
          release(connection);
          if (connection.allocations.isEmpty()) {
            connection.idleAtNanos = System.nanoTime();
            if (Internal.instance.connectionBecameIdle(connectionPool, connection)) {
              socket = connection.socket();
            }
          }
          connection = null;
        }
      }
      return socket;
    }
    
    

    果然咯,调用私有的release(在allocations里找到当前StreamAllocation并移除)。当allocations为空时返回socket,否则返回null。中间执行connectionBecameIdle,通知ConnectionPool清除这个空闲连接。

    连接管理

    okhttp使用ConnectionPool管理连接,里面有一个Deque保存所有的连接。

    private final Deque<RealConnection> connections = new ArrayDeque<>();
    

    ConnectionPool对象直接在OkHttpClient中new出来,但是访问需要通过在static{}中定义的Internal.instance(为了让外部包的成员访问非public方法)。

    ConnectionPool里增减连接的方法有下面几个:

    • put
    • get
    • connectionBecameIdle
    • evictAll

    看方法名就知道用途,基本是对Deque的操作,看看get方法:

    @Nullable RealConnection get(Address address, StreamAllocation streamAllocation, Route route) {
       assert (Thread.holdsLock(this));
       for (RealConnection connection : connections) {
         if (connection.isEligible(address, route)) {
           streamAllocation.acquire(connection, true);
           return connection;
         }
       }
       return null;
     }
    

    获取一个连接需要满足一定的条件,如果能够获取连接,调用streamAllocation.acquire增加一个流。

    void put(RealConnection connection) {
      assert (Thread.holdsLock(this));
      if (!cleanupRunning) {
        cleanupRunning = true;
        executor.execute(cleanupRunnable);
      }
      connections.add(connection);
    }
    
    

    put方法直接向connections加入一个连接,加入之前会尝试执行清理工作,触发cleanupRunnable,提交到ConnectionPool内部的线程池执行。

    while (true) {
      long waitNanos = cleanup(System.nanoTime());
      if (waitNanos == -1) return;
      if (waitNanos > 0) {
        long waitMillis = waitNanos / 1000000L;
        waitNanos -= (waitMillis * 1000000L);
        synchronized (ConnectionPool.this) {
          try {
            ConnectionPool.this.wait(waitMillis, (int) waitNanos);
          } catch (InterruptedException ignored) {
          }
        }
      }
    }
    

    执行清理的线程是个无限循环,cleanup执行清理并返回下次清理的时间,然后进入wait。

    boolean connectionBecameIdle(RealConnection connection) {
      assert (Thread.holdsLock(this));
      if (connection.noNewStreams || maxIdleConnections == 0) {
        connections.remove(connection);
        return true;
      } else {
        notifyAll(); // Awake the cleanup thread: we may have exceeded the idle connection limit.
        return false;
      }
    }
    

    当一个连接变为空闲时,需要notifyAll,唤醒的就是清理线程。

    具体清理过程的方法cleanup比较长,归纳出伪码:

    for 所有连接{
        1、检查连接是否空闲
        2、空闲数量+1
        3、标记空闲最久的连接
    }
    
    if 空闲时间大于keep-alive时间 或 空闲连接大于5个
        移除空闲最久的连接,最后return 0,马上触发下一次cleanup
    else if 有空闲连接
        return 空闲最久连接剩余到期时间
    else if 有在用连接
        return keep-alive
    else 没有连接
        return -1 跳出清理线程
    
    return 0
    

    keep-alive时间在ConnectionPool预设的时间是5分钟,最大空闲连接数量是5个,可以修改。

    连接清理剩下最后一个问题,如何判断连接在用呢。回想RealConnection维护的allocations列表,对StreamAllocation使用了弱引用包装。只要弱引用还存在,说明连接还在用。

    pruneAndGetAllocationCount检查连接上每个流,并返回在用流的数量。

    相关文章

      网友评论

          本文标题:okhttp 3.10连接复用原理

          本文链接:https://www.haomeiwen.com/subject/iutbuftx.html