天天看點

OkHttp3源碼詳解(五)okhttp連接配接池複用機制1、概述2、連接配接池的使用

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進行操作的方法分别為put、get、connectionBecameIdle、evictAll幾個操作。分别對應放入連接配接、擷取連接配接、移除連接配接、移除所有連接配接操作。

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> 存放在RealConnection連接配接對象中用于記錄Connection的活躍情況。

連接配接池中Connection的緩存比較簡單,就是利用一個雙端清單,配合CRD等操作。那麼connection在timeout時間類是如果失效的呢,并且如果做到有效的對連接配接進行清除操作以確定性能和記憶體空間的充足。

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> 就是一個記錄connection活躍情況的 >0表示活躍 =0 表示空閑。StreamAllocation 在清單中的數量就是就是實體socket被引用的次數

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

搞定了查找閑置的connection操作,我們回到cleanup 的操作。計算了inUseConnectionCount和idleConnectionCount 之後程式又根據閑置時間對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> 和 選擇排序的算法以及excutor的清理線程池。

原文連結

https://www.cnblogs.com/ganchuanpu/p/9408081.html