接主文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比較長(zhǎng),歸納出偽碼:
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ù)量匙瘪。