Okhttp3源碼解析(4)-攔截器與設計模式

来源:https://www.cnblogs.com/qinzishuai/archive/2019/08/27/11416058.html
-Advertisement-
Play Games

### 前言 回顧: [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源碼解析(1)-OkHttpClient分析](https://www.jianshu.com/p/bf1d01b79ce7) [Okhttp3源碼解析( ...


### 前言 回顧: [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源碼解析(1)-OkHttpClient分析](https://www.jianshu.com/p/bf1d01b79ce7) [Okhttp3源碼解析(2)-Request分析](https://www.jianshu.com/p/5a85345c8ea7) [Okhttp3源碼解析(3)-Call分析(整體流程)](https://www.jianshu.com/p/4ed79472797a) 上節我們講了okhttp的整體的流程,裡面的核心方法之一是`getResponseWithInterceptorChain()` ,這個方法應該知道吧?通過攔截器層層處理返回Response;這個方法中其實應用了責任鏈設計模式。今天主要講一下它是如何應用的! ### 責任鏈設計模式 ###### 責任鏈模式的定義 在責任鏈模式里,很多對象由每一個對象對其下家的引用而連接起來形成一條鏈。請求在這個鏈上傳遞,直到鏈上的某一個對象決定處理此請求。發出這個請求的客戶端並不知道鏈上的哪一個對象最終處理這個請求,這使得系統可以在不影響客戶端的情況下動態地重新組織和分配責任。 模型: ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082427829-283762395.png) 1.優點 耦合度降低,請求和處理是分開的 2.缺點 責任鏈太長或者每條鏈判斷處理的時間太長會影響性能。特別是遞歸迴圈的時候 不一定被處理,每個職責類的職責很明確,這就需要對寫預設的處理了 **責任鏈模式重要的兩點:分離職責,動態組合** 對責任鏈設計模式不明白的可以去網上那個找找實例看看, 這裡就不舉例子了。 ### 源碼中的責任鏈 話不多說,直接上`getResponseWithInterceptorChain()` 源碼 ``` Response getResponseWithInterceptorChain() throws IOException { // Build a full stack of interceptors. List interceptors = new ArrayList<>(); interceptors.addAll(client.interceptors()); //自定義 interceptors.add(retryAndFollowUpInterceptor); //錯誤與跟蹤攔截器 interceptors.add(new BridgeInterceptor(client.cookieJar())); //橋攔截器 interceptors.add(new CacheInterceptor(client.internalCache())); //緩存攔截器 interceptors.add(new ConnectInterceptor(client)); //連接攔截器 if (!forWebSocket) { interceptors.addAll(client.networkInterceptors()); //網路攔截器 } interceptors.add(new CallServerInterceptor(forWebSocket)); //調用伺服器攔截器 Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest, this, eventListener, client.connectTimeoutMillis(), client.readTimeoutMillis(), client.writeTimeoutMillis()); return chain.proceed(originalRequest); } ``` 方法中大部分上節已經說了,就是 `List`添加自定義、cookie等等的攔截器,今天我們主要看看後半部分: ``` Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest, this, eventListener, client.connectTimeoutMillis(), client.readTimeoutMillis(), client.writeTimeoutMillis()); return chain.proceed(originalRequest); ``` 首先初始化了 `RealInterceptorChain`,`RealInterceptorChain`是`Interceptor.Chain`的實現類 ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082428677-935973782.png) 先看一下`Interceptor.Chain`: ``` public interface Interceptor { Response intercept(Chain chain) throws IOException; interface Chain { Request request(); Response proceed(Request request) throws IOException; //部分代碼省略.... } } ``` 生成了RealInterceptorChain的實例,調用了`proceed()`,返回了最後的Response 我們看下 `RealInterceptorChain`類中的`proceed()`: ``` @Override public Response proceed(Request request) throws IOException { return proceed(request, streamAllocation, httpCodec, connection); } public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException { if (index >= interceptors.size()) throw new AssertionError(); calls++; // If we already have a stream, confirm that the incoming request will use it. if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) { throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must retain the same host and port"); } // If we already have a stream, confirm that this is the only call to chain.proceed(). if (this.httpCodec != null && calls > 1) { throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must call proceed() exactly once"); } // Call the next interceptor in the chain. RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + 1, request, call, eventListener, connectTimeout, readTimeout, writeTimeout); Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(next); // Confirm that the next interceptor made its required call to chain.proceed(). if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) { throw new IllegalStateException("network interceptor " + interceptor + " must call proceed() exactly once"); } // Confirm that the intercepted response isn't null. if (response == null) { throw new NullPointerException("interceptor " + interceptor + " returned null"); } if (response.body() == null) { throw new IllegalStateException( "interceptor " + interceptor + " returned a response with no body"); } return response; } ``` 經過一系列的判斷,看下`proceed()`的核心 ``` // Call the next interceptor in the chain. RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + 1, request, call, eventListener, connectTimeout, readTimeout, writeTimeout); Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(next); ``` 如果對責任鏈模式有認識的朋友看到上面代碼,應該直接就能看出來了,**並能分析出:** - 如果是責任鏈模式, 那個`intercept()`一定是關鍵, `Interceptor`是介面,interceptors集合中的攔截器類肯定都實現了 `Interceptor`以及 `interceptor.intercept()` - 每個攔截器 `intercept() `方法中的chain,都在上一個 `chain`實例的 `chain.proceed() `中被初始化,並傳遞了攔截器List與 `index `,直接最後一個 `chain實例 `執行即停止。 ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082428850-1579043948.png) ### 總結: 每個`chain`的`interceptors`與`index`都是由上一個`chain`初始化傳遞過來的,在`chain.proceed()`中獲取對應的`interceptor實例` 並初始化下一個`chain`,直到最後一個`chain`被執行。 這樣就清晰了吧?責任鏈模式的重點在“鏈上”,由一條鏈去處理相似的請求,在鏈中決定誰來處理這個請求,並返回相應的結果。 ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082429260-1507882191.png) 這節就說到這,希望對大家有所幫助..... 大家可以關註我的微信公眾號:「秦子帥」一個有質量、有態度的公眾號! ![公眾號](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082429414-2044533379.jpg)
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Linux 基礎學習2 [TOC] 文件目錄結構 文件和目錄被組織成一顆倒置的樹狀結構 文件系統從根開始,“/” 文件名稱嚴格區分大小寫 隱藏文件以"."開頭 路徑的分隔符為"/" 文件命名規範 文件字元最長為255個字元 包括路徑在內文件名稱最長為4095個 顏色表示 藍色文件 目錄 綠色文件 可 ...
  • vim是linux和mac中常用到的編輯器。 其分為4種模式: normal模式:普通模式,瀏覽作用 insert模式: i(insert) 在當前游標處進行插入 a(append) 在當前游標後進行插入 o(open a line below) 在當前行下進行插入 I 在當前行首進行插入 A 在當 ...
  • 分區的基礎知識: 模式:mbr分區: 1、最多支持四個主分區 2、系統只能安裝主分區 3、擴展分區要占一個主分區 4、MBR最大隻支持2TB,但擁有最好的相容性 gtp分區: 1、支持無限多個主分區(但操作系統可能限制,比如windows下最多128個分區) 2、最大支持18EB的大容量(EB=10 ...
  • DATEPART() 函數用於返回日期/時間的單獨部分,比如年、月、日、小時、分鐘等等。 DATEDIFF() 函數返回兩個日期之間的時間差。 計算兩個時間差 相差年數:SELECT DATEDIFF(YEAR,'2017-07-01 11:25:52','2018-07-02 12:25:52') ...
  • 一、Phoenix簡介 是 HBase 的開源 SQL 中間層,它允許你使用標準 JDBC 的方式來操作 HBase 上的數據。在 之前,如果你要訪問 HBase,只能調用它的 Java API,但相比於使用一行 SQL 就能實現數據查詢,HBase 的 API 還是過於複雜。 的理念是 ,即你可以 ...
  • 腳本: 腳本運行結果: ...
  • 一、前言 本文主要介紹 Hbase 常用的三種簡單的容災備份方案,即 CopyTable 、 Export / Import 、 Snapshot 。分別介紹如下: 二、CopyTable 2.1 簡介 CopyTable 可以將現有表的數據複製到新表中,具有以下特點: 支持時間區間 、row 區間 ...
  • 如果補丁中有online目錄就是線上補丁,不需要資料庫停機,線上的又分集群和非集群,如下查看readme可以得知線上補丁打法$ cat README.txt Oracle Database 11g Release 11.2.0.3.0ORACLE DATABASE Patch for Bug# 12... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...