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

前言

回顧: Okhttp的基本用法 Okhttp3源碼解析(1)-OkHttpClient分析 Okhttp3源碼解析(2)-Request分析 Okhttp3源碼解析(3)-Call分析(總體流程)設計模式

上節咱們講了okhttp的總體的流程,裏面的核心方法之一是getResponseWithInterceptorChain() ,這個方法應該知道吧?經過攔截器層層處理返回Response;這個方法中其實應用了責任鏈設計模式。今天主要講一下它是如何應用的!緩存

責任鏈設計模式

責任鏈模式的定義

在責任鏈模式裏,不少對象由每個對象對其下家的引用而鏈接起來造成一條鏈。請求在這個鏈上傳遞,直到鏈上的某一個對象決定處理此請求。發出這個請求的客戶端並不知道鏈上的哪個對象最終處理這個請求,這使得系統能夠在不影響客戶端的狀況下動態地從新組織和分配責任。服務器

模型:微信

1.優勢 耦合度下降,請求和處理是分開的 2.缺點 責任鏈太長或者每條鏈判斷處理的時間太長會影響性能。特別是遞歸循環的時候 不必定被處理,每一個職責類的職責很明確,這就須要對寫默認的處理了 責任鏈模式重要的兩點:分離職責,動態組合 對責任鏈設計模式不明白的能夠去網上那個找找實例看看, 這裏就不舉例子了。cookie

源碼中的責任鏈

話很少說,直接上getResponseWithInterceptorChain() 源碼網絡

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> 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<Interceptor>添加自定義、cookie等等的攔截器,今天咱們主要看看後半部分:ide

Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());   

    return chain.proceed(originalRequest);

首先初始化了 RealInterceptorChainRealInterceptorChainInterceptor.Chain的實現類 性能

先看一下Interceptor.Chainui

public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();

    Response proceed(Request request) throws IOException;

//部分代碼省略....
  }
}

生成了RealInterceptorChain的實例,調用了proceed(),返回了最後的Response 咱們看下 RealInterceptorChain類中的proceed()this

@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實例 執行即中止。

總結:

每一個chaininterceptorsindex都是由上一個chain初始化傳遞過來的,在chain.proceed()中獲取對應的interceptor實例 並初始化下一個chain,直到最後一個chain被執行。

這樣就清晰了吧?責任鏈模式的重點在「鏈上」,由一條鏈去處理類似的請求,在鏈中決定誰來處理這個請求,並返回相應的結果。

這節就說到這,但願對你們有所幫助.....

你們能夠關注個人微信公衆號:「秦子帥」一個有質量、有態度的公衆號!

公衆號

相關文章
相關標籤/搜索