接主文okhttp3.10介紹okhttp的連接復(fù)用。
Keep-Alive機(jī)制:當(dāng)一個(gè)http請(qǐng)求完成后,tcp連接不會(huì)立即釋放,如果有新的http請(qǐng)求,并且host和上次一樣,那么可以復(fù)用tcp連接,省去重新連接的過程。
如果沒有開啟Keep-Alive,一個(gè)http請(qǐng)求就需要一次tcp連接,非常浪費(fèi)資源。我們來看okhttp與連接相關(guān)的四個(gè)類,重點(diǎn)看連接的管理。
- Collection
- HttpCodec
- StreamAllocation
- ConnectionPool
連接和流
public interface Connection {
Route route();
Socket socket();
@Nullable Handshake handshake();
Protocol protocol();
}
Connection描述http的物理連接,封裝了Socket,具體的實(shí)現(xiàn)類是RealConnection,其他三個(gè)變量Route、Handshake、Protocol是http協(xié)議相關(guān)類。(只要知道Connection是請(qǐng)求發(fā)送和響應(yīng)的通道,真系要進(jìn)入http原理時(shí)再講)
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,它是一個(gè)比java.io更高效的庫(具體原理先book定下一篇講)。Source和Sink,分別對(duì)應(yīng)java.io的InputStream和OutputStream,就是輸入輸出。
http1和http2有不同的實(shí)現(xiàn),http2是未來,看Http1Codec的。
在http1.1,一個(gè)連接只能有一個(gè)流,而在http2則可以支持多個(gè)流。為了管理一個(gè)連接上的多個(gè)流,okhttp使用StreamAllocation作為連接和流的橋梁。在RealConnection中保存了StreamAllocationd的一個(gè)列表,作為連接上流的計(jì)數(shù)器。如果列表大小為0,表示連接是空閑的,可以回收;否則連接還在用,不能關(guān)閉。
public final List<Reference<StreamAllocation>> allocations = new ArrayList<>();
操作allocations對(duì)應(yīng)的增減方法是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));
}
為連接新增一個(gè)流,StreamAllocation用弱引用包裝為StreamAllocationReference,直接加入allocations。
釋放StreamAllocation管理的流的方法有兩個(gè),一個(gè)供外部調(diào)用,public、沒入?yún)⒌膔elease:
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);
}
}
最重要是調(diào)用deallocate,為什么返回socket并嘗試執(zhí)行關(guān)閉呢?連接上可能有多個(gè)流喔!可以猜想到deallocate肯定操作減少allocations,當(dāng)allocations空了,返回連接的socket關(guān)閉。
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;
}
果然咯,調(diào)用私有的release(在allocations里找到當(dāng)前StreamAllocation并移除)。當(dāng)allocations為空時(shí)返回socket,否則返回null。中間執(zhí)行connectionBecameIdle,通知ConnectionPool清除這個(gè)空閑連接。
連接管理
okhttp使用ConnectionPool管理連接,里面有一個(gè)Deque保存所有的連接。
private final Deque<RealConnection> connections = new ArrayDeque<>();
ConnectionPool對(duì)象直接在OkHttpClient中new出來,但是訪問需要通過在static{}中定義的Internal.instance(為了讓外部包的成員訪問非public方法)。
ConnectionPool里增減連接的方法有下面幾個(gè):
- put
- get
- connectionBecameIdle
- evictAll
看方法名就知道用途,基本是對(duì)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;
}
獲取一個(gè)連接需要滿足一定的條件,如果能夠獲取連接,調(diào)用streamAllocation.acquire增加一個(gè)流。
void put(RealConnection connection) {
assert (Thread.holdsLock(this));
if (!cleanupRunning) {
cleanupRunning = true;
executor.execute(cleanupRunnable);
}
connections.add(connection);
}
put方法直接向connections加入一個(gè)連接,加入之前會(huì)嘗試執(zhí)行清理工作,觸發(fā)cleanupRunnable,提交到ConnectionPool內(nèi)部的線程池執(zhí)行。
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) {
}
}
}
}
執(zhí)行清理的線程是個(gè)無限循環(huán),cleanup執(zhí)行清理并返回下次清理的時(shí)間,然后進(jìn)入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;
}
}
當(dāng)一個(gè)連接變?yōu)榭臻e時(shí),需要notifyAll,喚醒的就是清理線程。
具體清理過程的方法cleanup比較長,歸納出偽碼:
for 所有連接{
1、檢查連接是否空閑
2、空閑數(shù)量+1
3、標(biāo)記空閑最久的連接
}
if 空閑時(shí)間大于keep-alive時(shí)間 或 空閑連接大于5個(gè)
移除空閑最久的連接,最后return 0,馬上觸發(fā)下一次cleanup
else if 有空閑連接
return 空閑最久連接剩余到期時(shí)間
else if 有在用連接
return keep-alive
else 沒有連接
return -1 跳出清理線程
return 0
keep-alive時(shí)間在ConnectionPool預(yù)設(shè)的時(shí)間是5分鐘,最大空閑連接數(shù)量是5個(gè),可以修改。
連接清理剩下最后一個(gè)問題,如何判斷連接在用呢。回想RealConnection維護(hù)的allocations列表,對(duì)StreamAllocation使用了弱引用包裝。只要弱引用還存在,說明連接還在用。
pruneAndGetAllocationCount檢查連接上每個(gè)流,并返回在用流的數(shù)量。