這一篇主要分析RetryAndFollowUpInterceptor這個(gè)過(guò)濾器杜窄,這個(gè)過(guò)濾器的職責(zé)是重試和重定向栽渴。通過(guò)前面一篇文章互妓,我們知道一個(gè)過(guò)濾器的功能,重點(diǎn)都在他重寫Interceptor的intercept(Chain chain)方法冬耿。下面是該攔截器的intercept源碼
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();
//streamAllocation的創(chuàng)建位置
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
call, eventListener, callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
//取消
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), false, request)) {
throw e.getLastConnectException();
}
releaseConnection = false;
//重試...
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
//先判斷當(dāng)前請(qǐng)求是否已經(jīng)發(fā)送了
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
//同樣的重試判斷
if (!recover(e, requestSendStarted, request)) throw e;
releaseConnection = false;
//重試...
continue;
} finally {
// We're throwing an unchecked exception. Release any resources.
//沒(méi)有捕獲到的異常舌菜,最終要釋放
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// Attach the prior response if it exists. Such responses never have a body.
//這里基本上都沒(méi)有講,priorResponse是用來(lái)保存前一個(gè)Resposne的亦镶,這里可以看到將前一個(gè)Response和當(dāng)前的Resposne
//結(jié)合在一起了酷师,對(duì)應(yīng)的場(chǎng)景是,當(dāng)獲得Resposne后染乌,發(fā)現(xiàn)需要重定向,則將當(dāng)前Resposne設(shè)置給priorResponse懂讯,再執(zhí)行一遍流程荷憋,
//直到不需要重定向了,則將priorResponse和Resposne結(jié)合起來(lái)褐望。
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
//判斷是否需要重定向,如果需要重定向則返回一個(gè)重定向的Request勒庄,沒(méi)有則為null
Request followUp = followUpRequest(response);
if (followUp == null) {
//不需要重定向
if (!forWebSocket) {
//是WebSocket,釋放
streamAllocation.release();
}
//返回response
return response;
}
//需要重定向,關(guān)閉響應(yīng)流
closeQuietly(response.body());
//重定向次數(shù)++,并且小于最大重定向次數(shù)MAX_FOLLOW_UPS(20)
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
//是UnrepeatableRequestBody瘫里, 剛才看過(guò)也就是是流類型实蔽,沒(méi)有被緩存,不能重定向
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
}
//判斷是否相同谨读,不然重新創(chuàng)建一個(gè)streamConnection
if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(followUp.url()), call, eventListener, callStackTrace);
} else if (streamAllocation.codec() != null) {
throw new IllegalStateException("Closing the body of " + response
+ " didn't close its backing stream. Bad interceptor?");
}
//賦值再來(lái)局装!
request = followUp;
priorResponse = response;
}
}
RetryAndFollowUpInterceptor 是 OKHTTP 內(nèi)置中的第一個(gè)攔截器,其功能主要有以下幾點(diǎn):
1.創(chuàng)建 StreamAllocation 對(duì)象劳殖;
2.調(diào)用 RealInterceptorChain.proceed(...)進(jìn)行網(wǎng)絡(luò)請(qǐng)求铐尚;
3.根據(jù)異常結(jié)果或者響應(yīng)結(jié)果判斷是否要進(jìn)行重新請(qǐng)求。
注意第二和第三點(diǎn)是在 while (true)內(nèi)部執(zhí)行的哆姻,也就是系統(tǒng)通過(guò)死循環(huán)來(lái)實(shí)現(xiàn)重連機(jī)制宣增。下面閱讀 OKHTTP 源碼來(lái)看 RetryAndFollowUpInterceptor 內(nèi)部是怎么實(shí)現(xiàn)以上 3 點(diǎn)功能的。
1矛缨、創(chuàng)建 StreamAllocation 對(duì)象
StreamAllocation 在 RetryAndFollowUpInterceptor 創(chuàng)建爹脾,它會(huì)在 ConnectInterceptor 中真正被使用到帖旨,主要就是用于獲取連接服務(wù)端的 Connection 和用于進(jìn)行跟服務(wù)端進(jìn)行數(shù)據(jù)傳輸?shù)妮斎胼敵隽?HttpStream,具體的操作不是這篇博客的重點(diǎn)灵妨,只要了解它的作用的就行了解阅。
2、網(wǎng)絡(luò)請(qǐng)求
因?yàn)樵?OKHTTP 中的攔截器的執(zhí)行過(guò)程是一個(gè)遞歸的過(guò)程闷串,也就是它內(nèi)部會(huì)通過(guò) RealInterceptorChain 這個(gè)類去負(fù)責(zé)將所有的攔截器進(jìn)行串起來(lái)瓮钥。只有所有的攔截器執(zhí)行完畢之后,一個(gè)網(wǎng)絡(luò)請(qǐng)求的響應(yīng) Response 才會(huì)被返回烹吵。
但是呢碉熄,在執(zhí)行這個(gè)過(guò)程中,難免會(huì)出現(xiàn)一些問(wèn)題肋拔,例如連接中斷锈津,握手失敗或者服務(wù)器檢測(cè)到未認(rèn)證等,那么這個(gè) resposne 的返回碼就不是正常的 200 了凉蜂,因此說(shuō)這個(gè) response 并不一定是可用的琼梆,或者說(shuō)在請(qǐng)求過(guò)程就已經(jīng)拋出異常了,例如超時(shí)異常等窿吩,那么 RetryAndFollowUpInterceptor 需要依據(jù)這些問(wèn)題進(jìn)行判斷是否可以進(jìn)行重新連接茎杂。
while(true){
try{
...
response = ((RealInterceptorChain) chain).proceed(request,
streamAllocation, null, null);
...
}catch(RouteException e){
//判斷 RouteException 否可以重連
}catch(IOException e){
//判斷 IOException 否可以重連
}finally{
//釋放流
}
...
}
3、 網(wǎng)絡(luò)請(qǐng)求異常的“重連機(jī)制”
public Response proceed(Request request, StreamAllocation
streamAllocation, HttpStream httpStream,Connection connection) throws IOException {
在上面已經(jīng)介紹過(guò)了網(wǎng)絡(luò)請(qǐng)求時(shí)通過(guò) RealInterceptorChain#proceed 方法進(jìn)行的纫雁,該方法的聲明中拋出了 IOException 煌往,表示在整個(gè)網(wǎng)絡(luò)請(qǐng)求過(guò)程有可能出現(xiàn) IOException,但是我們看了在 catch 中還有一個(gè)異常那就是 RouteException轧邪,下面是兩個(gè)異常的繼承結(jié)構(gòu):
IOException 它是編譯時(shí)刽脖,需要在編譯時(shí)期就要捕獲或者拋出。
public class IOException extends Exception
RouteException 是運(yùn)行時(shí)異常忌愚,不需要顯示的去捕獲或者拋出曲管。
public final class RouteException extends RuntimeException
try {
//網(wǎng)絡(luò)請(qǐng)求
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
//表示是否要釋放連接,在 finally 中會(huì)使用到硕糊。
releaseConnection = false;
} catch (RouteException e) {
//路由異常RouteException
// The attempt to connect via a route failed. The request will not have been sent.
//檢測(cè)路由異常是否能重新連接
if (!recover(e.getLastConnectException(), true, request)) throw e.getLastConnectException();
//可以重新連接院水,那么就不要釋放連接
releaseConnection = false;
//重新進(jìn)行while循環(huán),進(jìn)行網(wǎng)絡(luò)請(qǐng)求
continue;
} catch (IOException e) {
//檢測(cè)該IO異常是否能重新連接
// An attempt to communicate with a server failed. The request may have been sent.
if (!recover(e, false, request)) throw e;
//可以重新連接癌幕,那么就不要釋放連接
releaseConnection = false;
//重新進(jìn)行while循環(huán)衙耕,進(jìn)行網(wǎng)絡(luò)請(qǐng)求
continue;
} finally {
//當(dāng) releaseConnection 為true時(shí)表示需要釋放連接了。
// We're throwing an unchecked exception. Release any resources.
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
3.1勺远、RouteException 異常的重連機(jī)制
在 RouteException 的重連機(jī)制主要做了這樣幾件事:
通過(guò) recover 方法檢測(cè)該 RouteException 是否能重新連接橙喘;
可以重新連接,那么就不要釋放連接 releaseConnection = false胶逢;
continue進(jìn)入下一次循環(huán)厅瞎,進(jìn)行網(wǎng)絡(luò)請(qǐng)求饰潜;
不可以重新連接就直接走 finally 代碼塊釋放連接。
下面是通過(guò) find Usages 得到 RouteException 被哪里拋出的圖和簸,從圖可以看出 RouteException 是在獲取一個(gè) HttpStream 流和與 SOCKET 建立連接時(shí)出現(xiàn)異常才被拋出的彭雾,在拋異常的方法內(nèi)部并沒(méi)有顯示地去捕獲,因此異常會(huì)被 RetryAndFollowUpInterceptor#intercept 中的 catch 捕獲锁保,下面就是對(duì)捕獲的異常的處理薯酝。
查看源碼可以知道 RouteException 和 IOException 異常檢測(cè)都會(huì)調(diào)用 recover 方法進(jìn)行判斷,主要是第二個(gè)參數(shù)不一樣爽柒,這里傳入的是true吴菠,表示該異常是 RouteException ,下面 IOException 檢測(cè)時(shí)傳入的參數(shù)時(shí) false 浩村。
if (!recover(e.getLastConnectException(), true, request)) throw
e.getLastConnectException();
3.2做葵、 recover 方法異常檢測(cè)
private boolean recover(IOException e, boolean routeException, Request userRequest) {
streamAllocation.streamFailed(e);
//1.判斷 OkHttpClient 是否支持失敗重連的機(jī)制
// The application layer has forbidden retries.
if (!client.retryOnConnectionFailure()) return false;
// 在該方法中傳入的 routeException值 為 true
// We can't send the request body again.
if (!routeException && userRequest.body() instanceof UnrepeatableRequestBody) return false;
//2.isRecoverable 檢測(cè)該異常是否是致命的。
// This exception is fatal.
if (!isRecoverable(e, routeException)) return false;
// No more routes to attempt.
//3.是否有更多的路線
if (!streamAllocation.hasMoreRoutes()) return false;
// For failure recovery, use the same route selector with a new connection.
return true;
}
從上面源碼可以看出 recover 方法主要做了以下幾件事:
1.判斷 OkHttpClient 是否支持失敗重連的機(jī)制心墅;
如果不支持重連酿矢,就表示請(qǐng)求失敗就失敗了,不能再重試了怎燥。
2.通過(guò) isRecoverable 方法檢測(cè)該異常是否是致命的瘫筐;
3.是否有更多的路線,可以重試铐姚。
3.3严肪、isRecoverable 方法異常檢測(cè)
在該方法中會(huì)檢測(cè)異常是否為嚴(yán)重異常,嚴(yán)重異常就不要進(jìn)行重連了谦屑,下面檢測(cè)的異常都做了注釋。這里涉及到一個(gè)
SocketTimeoutException 的異常篇梭,表示連接超時(shí)異常氢橙,這個(gè)異常還是可以進(jìn)行重連的,也就是說(shuō)** OKHTTP 內(nèi)部在連接超時(shí)時(shí)是會(huì)自動(dòng)進(jìn)行重連的恬偷。**
private boolean isRecoverable(IOException e, boolean routeException) {
//ProtocolException 這種異常屬于嚴(yán)重異常悍手,不能進(jìn)行重新連接
// If there was a protocol problem, don't recover.
if (e instanceof ProtocolException) {
return false;
}
//當(dāng)異常為中斷異常時(shí)
// If there was an interruption don't recover, but if there was a timeout connecting to a route
// we should try the next route (if there is one).
if (e instanceof InterruptedIOException) {
return e instanceof SocketTimeoutException && routeException;
}
// Look for known client-side or negotiation errors that are unlikely to be fixed by trying
// again with a different route.
//握手異常
if (e instanceof SSLHandshakeException) {
// If the problem was a CertificateException from the X509TrustManager,
// do not retry.
if (e.getCause() instanceof CertificateException) {
return false;
}
}
//驗(yàn)證異常
if (e instanceof SSLPeerUnverifiedException) {
// e.g. a certificate pinning error.
return false;
}
// An example of one we might want to retry with a different route is a problem connecting to a
// proxy and would manifest as a standard IOException. Unless it is one we know we should not
// retry, we return true and try a new route.
return true;
}
3.4、IOException 異常的重連機(jī)制
IOException 異常的檢測(cè)實(shí)際上和 RouteException 是一樣的袍患,只是傳入 recover 方法的第二個(gè)參數(shù)為 false 而已坦康,表示該異常不是 RouteException ,這里就不分析了诡延。
4滞欠、followUpRequest 響應(yīng)碼檢測(cè)
當(dāng)代碼可以執(zhí)行到 followUpRequest 方法就表示這個(gè)請(qǐng)求是成功的,但是服務(wù)器返回的狀態(tài)碼可能不是 200 ok 的情況肆良,這時(shí)還需要對(duì)該請(qǐng)求進(jìn)行檢測(cè)筛璧,其主要就是通過(guò)返回碼進(jìn)行判斷的逸绎。
private Request followUpRequest(Response userResponse) throws IOException {
if (userResponse == null) throw new IllegalStateException();
Connection connection = streamAllocation.connection();
Route route = connection != null
? connection.route()
: null;
int responseCode = userResponse.code();
final String method = userResponse.request().method();
switch (responseCode) {
case HTTP_PROXY_AUTH:
Proxy selectedProxy = route != null
? route.proxy()
: client.proxy();
if (selectedProxy.type() != Proxy.Type.HTTP) {
throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
}
return client.proxyAuthenticator().authenticate(route, userResponse);
case HTTP_UNAUTHORIZED:
return client.authenticator().authenticate(route, userResponse);
case HTTP_PERM_REDIRECT:
case HTTP_TEMP_REDIRECT:
// "If the 307 or 308 status code is received in response to a request other than GET
// or HEAD, the user agent MUST NOT automatically redirect the request"
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// fall-through
case HTTP_MULT_CHOICE:
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
// Does the client allow redirects?
if (!client.followRedirects()) return null;
String location = userResponse.header("Location");
if (location == null) return null;
HttpUrl url = userResponse.request().url().resolve(location);
// Don't follow redirects to unsupported protocols.
if (url == null) return null;
// If configured, don't follow redirects between SSL and non-SSL.
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
if (!sameScheme && !client.followSslRedirects()) return null;
// Redirects don't include a request body.
Request.Builder requestBuilder = userResponse.request().newBuilder();
if (HttpMethod.permitsRequestBody(method)) {
if (HttpMethod.redirectsToGet(method)) {
requestBuilder.method("GET", null);
} else {
requestBuilder.method(method, null);
}
requestBuilder.removeHeader("Transfer-Encoding");
requestBuilder.removeHeader("Content-Length");
requestBuilder.removeHeader("Content-Type");
}
// When redirecting across hosts, drop all authentication headers. This
// is potentially annoying to the application layer since they have no
// way to retain them.
if (!sameConnection(userResponse, url)) {
requestBuilder.removeHeader("Authorization");
}
return requestBuilder.url(url).build();
case HTTP_CLIENT_TIMEOUT:
// 408's are rare in practice, but some servers like HAProxy use this response code. The
// spec says that we may repeat the request without modifications. Modern browsers also
// repeat the request (even non-idempotent ones.)
if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
}
return userResponse.request();
default:
return null;
}
}
5、重試次數(shù)判斷
在 RetryAndFollowUpInterceptor 內(nèi)部有一個(gè) MAX_FOLLOW_UPS 常量夭谤,它表示該請(qǐng)求可以重試多少次棺牧,在 OKHTTP 內(nèi)部中是不能超過(guò) 20 次,如果超過(guò) 20 次朗儒,那么就不會(huì)再請(qǐng)求了颊乘。
private static final int MAX_FOLLOW_UPS = 20;
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}