前言
網(wǎng)絡(luò)模塊在開發(fā)中很常見了吧,也可以說是很重要了吧动雹,所以梳理梳理槽卫,做做總結(jié) 、產(chǎn)出以及記錄胰蝠。
總的來說歼培,本文基于OkHttp4.5.0震蒋,Kotlin版本,做了對OkHttp的基本請求、整體流程、同/異步請求胡控、責(zé)任鏈調(diào)度以及CacheInterceptor的分析。
Http
網(wǎng)絡(luò)的底層蕾各,萬變不離其底層,這部分還是很重要的,以下兩篇都寫得非常nice
面試帶你飛:這是一份全面的 計算機網(wǎng)絡(luò)基礎(chǔ) 總結(jié)攻略
TCP協(xié)議靈魂之問,鞏固你的網(wǎng)路底層基礎(chǔ)
OkHttp
How 基本請求
fun load() {
//1.創(chuàng)建請求(包含url,method,headers,body)
val request = Request
.Builder()
.url("")
.build()
//2.創(chuàng)建OkHttpClient (包含分發(fā)器直砂、攔截器、DNS等)
val okHttpClient = OkHttpClient.Builder().build()
//3.創(chuàng)建Call(用于調(diào)用請求)
val newCall = okHttpClient.newCall(request)
//4.通過異步請求數(shù)據(jù)
newCall.enqueue(object :Callback{
override fun onFailure(call: Call, e: IOException) {}
override fun onResponse(call: Call, response: Response) {}
})
//4.通過同步請求數(shù)據(jù)
val response = newCall.execute()
}
- 流程圖
okhttp流程圖.png
前面就是基于構(gòu)造者的創(chuàng)建(主要是量太大,不想占篇幅所以就不展示出來了)
關(guān)鍵(并不)處在于RealCall的請求
- 1.異步請求 RealCall#enqueue(responseCallback: Callback)
//RealCall#enqueue(responseCallback: Callback)
override fun enqueue(responseCallback: Callback) {
synchronized(this) {
//檢查這個call是否已經(jīng)執(zhí)行過了丐枉,每 call只能被執(zhí)行一次
check(!executed) { "Already Executed" }
executed = true
}
//Call被調(diào)用時調(diào)用哆键,調(diào)用了EventListener#callStart()掘托、擴展此類可以監(jiān)視應(yīng)用程序的HTTP調(diào)用的數(shù)量瘦锹,大小和持續(xù)時間
callStart()
//1.這里創(chuàng)建了AsyncCall實際是個Runnable后面再提(標(biāo)記為3)
client.dispatcher.enqueue(AsyncCall(responseCallback))
}
//1.Dispatcher#enqueue(call: AsyncCall)
internal fun enqueue(call: AsyncCall) {
synchronized(this) {
//添加到異步調(diào)用的隊列
readyAsyncCalls.add(call)
if (!call.call.forWebSocket) {
val existingCall = findExistingCallWithHost(call.host)
if (existingCall != null) call.reuseCallsPerHostFrom(existingCall)
}
}
//2
promoteAndExecute()
}
//2.Dispatcher#promoteAndExecute()
//主要是將[readyAsyncCalls]過渡到[runningAsyncCalls]
private fun promoteAndExecute(): Boolean {
this.assertThreadDoesntHoldLock()
val executableCalls = mutableListOf<AsyncCall>()
val isRunning: Boolean
synchronized(this) {
val i = readyAsyncCalls.iterator()
while (i.hasNext()) {
val asyncCall = i.next()
if (runningAsyncCalls.size >= this.maxRequests) break // 最大容量. 64
if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue // 最大主機容量. 5
i.remove()
asyncCall.callsPerHost.incrementAndGet()
//異步請求各自添加到異步調(diào)用隊列和集合中
executableCalls.add(asyncCall)
runningAsyncCalls.add(asyncCall)
}
//同步隊列和異步隊列中超過一個 代表正在運行
isRunning = runningCallsCount() > 0
}
for (i in 0 until executableCalls.size) {
val asyncCall = executableCalls[i]
//3.
asyncCall.executeOn(executorService)
}
return isRunning
}
//3.RealCall.kt中的內(nèi)部類
internal inner class AsyncCall(
private val responseCallback: Callback
) : Runnable {
fun executeOn(executorService: ExecutorService) {
...
//有點長 直接說重點了
//放到線程池中 執(zhí)行這個Runnable
executorService.execute(this)
...
override fun run() {
threadName("OkHttp ${redactedUrl()}") {
...
try {
//兜兜轉(zhuǎn)轉(zhuǎn) 終于調(diào)用這個關(guān)鍵方法了
val response = getResponseWithInterceptorChain()
signalledCallback = true
//接口回調(diào)數(shù)據(jù)
responseCallback.onResponse(this@RealCall, response)
} catch (e: IOException) {
if (signalledCallback) {
Platform.get().log("Callback failure for ${toLoggableString()}", Platform.INFO, e)
} else {
responseCallback.onFailure(this@RealCall, e)
}
} catch (t: Throwable) {
cancel()
if (!signalledCallback) {
val canceledException = IOException("canceled due to $t")
canceledException.addSuppressed(t)
responseCallback.onFailure(this@RealCall, canceledException)
}
throw t
} finally {
//移除隊列
client.dispatcher.finished(this)
}
}
}
}
- 2.同步請求 RealCall#execute()
override fun execute(): Response {
//同樣判斷是否執(zhí)行過
synchronized(this) {
check(!executed) { "Already Executed" }
executed = true
}
timeout.enter()
//同樣監(jiān)聽
callStart()
try {
//同樣執(zhí)行
client.dispatcher.executed(this)
return getResponseWithInterceptorChain()
} finally {
//同樣移除
client.dispatcher.finished(this)
}
}
(Real)關(guān)鍵處的關(guān)鍵在于getResponseWithInterceptorChain()方法
@Throws(IOException::class)
internal fun getResponseWithInterceptorChain(): Response {
// 構(gòu)建完整的攔截器堆棧
val interceptors = mutableListOf<Interceptor>()
interceptors += client.interceptors //用戶自己攔截器
interceptors += RetryAndFollowUpInterceptor(client) //失敗后的重試和重定向
interceptors += BridgeInterceptor(client.cookieJar) //橋接用戶的信息和服務(wù)器的信息
interceptors += CacheInterceptor(client.cache) //處理緩存相關(guān)
interceptors += ConnectInterceptor //負責(zé)與服務(wù)器連接
if (!forWebSocket) {
interceptors += client.networkInterceptors //配置 OkHttpClient 時設(shè)置的
}
interceptors += CallServerInterceptor(forWebSocket) //負責(zé)向服務(wù)器發(fā)送請求數(shù)據(jù)、從服務(wù)器讀取響應(yīng)數(shù)據(jù)
//創(chuàng)建攔截鏈
val chain = RealInterceptorChain(
call = this,
interceptors = interceptors,
index = 0,
exchange = null,
request = originalRequest,
connectTimeoutMillis = client.connectTimeoutMillis,
readTimeoutMillis = client.readTimeoutMillis,
writeTimeoutMillis = client.writeTimeoutMillis
)
var calledNoMoreExchanges = false
try {
//攔截鏈的執(zhí)行 1.
val response = chain.proceed(originalRequest)
if (isCanceled()) {
response.closeQuietly()
throw IOException("Canceled")
}
return response
} catch (e: IOException) {
calledNoMoreExchanges = true
throw noMoreExchanges(e) as Throwable
} finally {
if (!calledNoMoreExchanges) {
noMoreExchanges(null)
}
}
}
//1.RealInterceptorChain#proceed(request: Request)
@Throws(IOException::class)
override fun proceed(request: Request): Response {
...
// copy出新的攔截鏈闪盔,鏈中的攔截器集合index+1
val next = copy(index = index + 1, request = request)
val interceptor = interceptors[index]
//調(diào)用攔截器的intercept(chain: Chain): Response 返回處理后的數(shù)據(jù) 交由下一個攔截器處理
@Suppress("USELESS_ELVIS")
val response = interceptor.intercept(next) ?: throw NullPointerException(
"interceptor $interceptor returned null")
...
//返回最終的響應(yīng)體
return response
}
這里采用責(zé)任鏈的模式來使每個功能分開弯院,每個Interceptor自行完成自己的任務(wù),并且將不屬于自己的任務(wù)交給下一個泪掀,簡化了各自的責(zé)任和邏輯听绳,和View中的事件分發(fā)機制類似.
- 再來一張時序圖
okhttp 時序圖.jpg
OkHttp關(guān)鍵中的核心就是這每一個攔截器 具體怎么實現(xiàn)還需要look look,這里就看一個CacheInterceptor吧
- CacheInterceptor.kt
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
//在Cache(DiskLruCache)類中 通過request.url匹配response
val cacheCandidate = cache?.get(chain.request())
//記錄當(dāng)前時間點
val now = System.currentTimeMillis()
//緩存策略 有兩種類型
//networkRequest 網(wǎng)絡(luò)請求
//cacheResponse 緩存的響應(yīng)
val strategy = CacheStrategy.Factory(now, chain.request(), cacheCandidate).compute()
val networkRequest = strategy.networkRequest
val cacheResponse = strategy.cacheResponse
//計算請求次數(shù)和緩存次數(shù)
cache?.trackResponse(strategy)
...
// 如果 禁止使用網(wǎng)絡(luò) 并且 緩存不足异赫,返回504和空body的Response
if (networkRequest == null && cacheResponse == null) {
return Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(HTTP_GATEWAY_TIMEOUT)
.message("Unsatisfiable Request (only-if-cached)")
.body(EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build()
}
// 如果策略中不能使用網(wǎng)絡(luò)椅挣,就把緩存中的response封裝返回
if (networkRequest == null) {
return cacheResponse!!.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build()
}
//調(diào)用攔截器process從網(wǎng)絡(luò)獲取數(shù)據(jù)
var networkResponse: Response? = null
try {
networkResponse = chain.proceed(networkRequest)
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
if (networkResponse == null && cacheCandidate != null) {
cacheCandidate.body?.closeQuietly()
}
}
//如果有緩存的Response
if (cacheResponse != null) {
//如果網(wǎng)絡(luò)請求返回code為304 即說明資源未修改
if (networkResponse?.code == HTTP_NOT_MODIFIED) {
//直接封裝封裝緩存的Response返回即可
val response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers, networkResponse.headers))
.sentRequestAtMillis(networkResponse.sentRequestAtMillis)
.receivedResponseAtMillis(networkResponse.receivedResponseAtMillis)
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build()
networkResponse.body!!.close()
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
cache!!.trackConditionalCacheHit()
cache.update(cacheResponse, response)
return response
} else {
cacheResponse.body?.closeQuietly()
}
}
val response = networkResponse!!.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build()
if (cache != null) {
//判斷是否具有主體 并且 是否可以緩存供后續(xù)使用
if (response.promisesBody() && CacheStrategy.isCacheable(response, networkRequest)) {
// 加入緩存中
val cacheRequest = cache.put(response)
return cacheWritingResponse(cacheRequest, response)
}
//如果請求方法無效 就從緩存中remove掉
if (HttpMethod.invalidatesCache(networkRequest.method)) {
try {
cache.remove(networkRequest)
} catch (_: IOException) {
// The cache cannot be written.
}
}
}
return response
}
總結(jié)
- OkHttpClient為Request創(chuàng)建RealCall
- RealCall的enqueue(responseCallback: Callback)異步請求通過Dispatcher實現(xiàn),和execute()同步請求一樣最終調(diào)用getResponseWithInterceptorChain()
- getResponseWithInterceptorChain()通過責(zé)任鏈模式用每個不同職責(zé)Interceptor處理Response返回數(shù)據(jù)
最后
- 如果文中如果有什么紕漏歡迎討論與指出。
- 參考
拆輪子系列:拆 OkHttp