OkHttp3源碼詳解(五) okhttp連接池復用機制


1、概述

提高網絡性能優化,很重要的一點就是降低延遲和提升響應速度。

通常我們在瀏覽器中發起請求的時候header部分往往是這樣的

keep-alive 就是瀏覽器和服務端之間保持長連接,這個連接是可以復用的。在HTTP1.1中是默認開啟的。

連接的復用為什么會提高性能呢? 
通常我們在發起http請求的時候首先要完成tcp的三次握手,然后傳輸數據,最后再釋放連接。三次握手的過程可以參考這里 TCP三次握手詳解及釋放連接過程

一次響應的過程

在高並發的請求連接情況下或者同個客戶端多次頻繁的請求操作,無限制的創建會導致性能低下。

如果使用keep-alive

在timeout空閑時間內,連接不會關閉,相同重復的request將復用原先的connection,減少握手的次數,大幅提高效率。

並非keep-alive的timeout設置時間越長,就越能提升性能。長久不關閉會造成過多的僵屍連接和泄露連接出現。

那么okttp在客戶端是如果類似於客戶端做到的keep-alive的機制。

2、連接池的使用

連接池的類位於okhttp3.ConnectionPool。我們的主旨是了解到如何在timeout時間內復用connection,並且有效的對其進行回收清理操作。

其成員變量代碼片

/**
 * Background threads are used to cleanup expired connections. There will be at most a single
 * thread running per connection pool. The thread pool executor permits the pool itself to be
 * garbage collected.
   */
  private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
      Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
      new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));

  /** The maximum number of idle connections for each address. */
  private final int maxIdleConnections;

  private final Deque<RealConnection> connections = new ArrayDeque<>();
  final RouteDatabase routeDatabase = new RouteDatabase();
  boolean cleanupRunning;
  • excutor : 線程池,用來檢測閑置socket並對其進行清理。
  • connections : connection緩存池。Deque是一個雙端列表,支持在頭尾插入元素,這里用作LIFO(后進先出)堆棧,多用於緩存數據。
  • routeDatabase :用來記錄連接失敗router

2.1 緩存操作

ConnectionPool提供對Deque<RealConnection>進行操作的方法分別為putgetconnectionBecameIdleevictAll幾個操作。分別對應放入連接、獲取連接、移除連接、移除所有連接操作。

put操作

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

可以看到在新的connection 放進列表之前執行清理閑置連接的線程。

既然是復用,那么看下他獲取連接的方式。

/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
RealConnection get(Address address, StreamAllocation streamAllocation) {
    assert (Thread.holdsLock(this));
    for (RealConnection connection : connections) {
      if (connection.allocations.size() < connection.allocationLimit
          && address.equals(connection.route().address)
          && !connection.noNewStreams) {
        streamAllocation.acquire(connection);
        return connection;
      }
    }
    return null;
 }

遍歷connections緩存列表,當某個連接計數的次數小於限制的大小以及request的地址和緩存列表中此連接的地址完全匹配。則直接復用緩存列表中的connection作為request的連接。

streamAllocation.allocations是個對象計數器,其本質是一個 List<Reference<StreamAllocation>> 存放在RealConnection連接對象中用於記錄Connection的活躍情況。

連接池中Connection的緩存比較簡單,就是利用一個雙端列表,配合CRD等操作。那么connectiontimeout時間類是如果失效的呢,並且如果做到有效的對連接進行清除操作以確保性能和內存空間的充足。

2.2 連接池的清理和回收

在看ConnectionPool的成員變量的時候我們了解到一個Executor的線程池是用來清理閑置的連接的。注釋中是這么解釋的:

 Background threads are used to cleanup expired connections

我們在put新連接到隊列的時候會先執行清理閑置連接的線程。調用的正是 executor.execute(cleanupRunnable); 方法。觀察cleanupRunnable

private final Runnable cleanupRunnable = new Runnable() {
    @Override public void run() {
      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 等待之后釋放鎖,繼續執行下一次的清理。所以可能理解成他是個監測時間並釋放連接的后台線程。

了解cleanup動作的過程。這里就是如何清理所謂閑置連接的和行了。怎么找到閑置的連接是主要解決的問題。

long cleanup(long now) {
    int inUseConnectionCount = 0;
    int idleConnectionCount = 0;
    RealConnection longestIdleConnection = null;
    long longestIdleDurationNs = Long.MIN_VALUE;

    // Find either a connection to evict, or the time that the next eviction is due.
    synchronized (this) {
      for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {
        RealConnection connection = i.next();

        // If the connection is in use, keep searching.
        if (pruneAndGetAllocationCount(connection, now) > 0) {
          inUseConnectionCount++;
          continue;
        }

        idleConnectionCount++;

        // If the connection is ready to be evicted, we're done.
        long idleDurationNs = now - connection.idleAtNanos;
        if (idleDurationNs > longestIdleDurationNs) {
          longestIdleDurationNs = idleDurationNs;
          longestIdleConnection = connection;
        }
      }

      if (longestIdleDurationNs >= this.keepAliveDurationNs
          || idleConnectionCount > this.maxIdleConnections) {
        // We've found a connection to evict. Remove it from the list, then close it below (outside
        // of the synchronized block).
        connections.remove(longestIdleConnection);
      } else if (idleConnectionCount > 0) {
        // A connection will be ready to evict soon.
        return keepAliveDurationNs - longestIdleDurationNs;
      } else if (inUseConnectionCount > 0) {
        // All connections are in use. It'll be at least the keep alive duration 'til we run again.
        return keepAliveDurationNs;
      } else {
        // No connections, idle or in use.
        cleanupRunning = false;
        return -1;
      }
    }

    closeQuietly(longestIdleConnection.socket());

    // Cleanup again immediately.
    return 0;
  }

在遍歷緩存列表的過程中,使用連接數目inUseConnectionCount 和閑置連接數目idleConnectionCount 的計數累加值都是通過pruneAndGetAllocationCount() 是否大於0來控制的。那么很顯然pruneAndGetAllocationCount() 方法就是用來識別對應連接是否閑置的。>0則不閑置。否則就是閑置的連接。

進去觀察

private int pruneAndGetAllocationCount(RealConnection connection, long now) {
    List<Reference<StreamAllocation>> references = connection.allocations;
    for (int i = 0; i < references.size(); ) {
      Reference<StreamAllocation> reference = references.get(i);

      if (reference.get() != null) {
        i++;
        continue;
      }

      // We've discovered a leaked allocation. This is an application bug.
      Platform.get().log(WARN, "A connection to " + connection.route().address().url()
          + " was leaked. Did you forget to close a response body?", null);
      references.remove(i);
      connection.noNewStreams = true;

      // If this was the last allocation, the connection is eligible for immediate eviction.
      if (references.isEmpty()) {
        connection.idleAtNanos = now - keepAliveDurationNs;
        return 0;
      }
    }

    return references.size();
  }
}

好了,原先存放在RealConnection 中的allocations 派上用場了。遍歷StreamAllocation 弱引用鏈表,移除為空的引用,遍歷結束后返回鏈表中弱引用的數量。所以可以看出List<Reference<StreamAllocation>> 就是一個記錄connection活躍情況的 >0表示活躍 =0 表示空閑。StreamAllocation 在列表中的數量就是就是物理socket被引用的次數

解釋:StreamAllocation被高層反復執行aquirerelease。這兩個函數在執行過程中其實是在一直在改變Connection中的 List<WeakReference<StreamAllocation>>大小。

搞定了查找閑置的connection操作,我們回到cleanup 的操作。計算了inUseConnectionCountidleConnectionCount 之后程序又根據閑置時間對connection進行了一個選擇排序,選擇排序的核心是:

 // If the connection is ready to be evicted, we're done.
        long idleDurationNs = now - connection.idleAtNanos;
        if (idleDurationNs > longestIdleDurationNs) {
          longestIdleDurationNs = idleDurationNs;
          longestIdleConnection = connection;
        }
      }
    ....

通過對比最大閑置時間選擇排序可以方便的查找出閑置時間最長的一個connection。如此一來我們就可以移除這個沒用的connection了!

 if (longestIdleDurationNs >= this.keepAliveDurationNs
          || idleConnectionCount > this.maxIdleConnections) {
        // We've found a connection to evict. Remove it from the list, then close it below (outside
        // of the synchronized block).
        connections.remove(longestIdleConnection);
}

總結:清理閑置連接的核心主要是引用計數器List<Reference<StreamAllocation>> 和 選擇排序的算法以及excutor的清理線程池。

部分參考:http://www.jianshu.com/p/92a61357164b

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM