OkHttp源碼(二)

由上篇分析了Ok請求的執(zhí)行流程知道辛辨,無論是同步還是異步召娜,最終得到網(wǎng)絡(luò)響應(yīng)玲销,都是通過調(diào)用getResponseWithInterceptorChain() 來獲取的,其內(nèi)部實(shí)現(xiàn)了一條攔截器鏈。下面開始分析源碼內(nèi)部的5個(gè)攔截器的調(diào)用劣欢,以及網(wǎng)絡(luò)數(shù)據(jù)的請求流程。

final class RealCall implements Call {
  //構(gòu)造一條攔截器鏈
  Response getResponseWithInterceptorChain() throws IOException {
    // 構(gòu)建一個(gè)列表來存放所有的攔截器
    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());
    }
    //網(wǎng)絡(luò)請求攔截器
    interceptors.add(new CallServerInterceptor(forWebSocket));
    
    //根據(jù)列表中的攔截器蜒秤,開始構(gòu)造一條攔截器鏈衅疙。
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());
    //開始整條鏈的調(diào)用
    return chain.proceed(originalRequest);
  }

用戶可以自定義自己的攔截器,并被首先添加到列表中溅呢,系統(tǒng)內(nèi)部自己實(shí)現(xiàn)了5個(gè)重要的攔截器澡屡,分別是RetryAndFollowUpInterceptor、BridgeInterceptor咐旧、CacheInterceptor驶鹉、ConnectInterceptor和CallServerInterceptor,整個(gè)攔截器鏈正是通過這5個(gè)攔截器串聯(lián)起來的铣墨。我們首先看proceed方法室埋,它接收了我們構(gòu)造的Request對象。

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

  interface Chain {
    Request request();

    Response proceed(Request request) throws IOException;
    ......
   }
}

Interceptor 是攔截器的接口伊约,由子類實(shí)現(xiàn)不同攔截器姚淆。Chain 是其內(nèi)部類,它由RealInterceptorChain屡律,構(gòu)成鏈的節(jié)點(diǎn)腌逢。

public final class RealInterceptorChain implements Interceptor.Chain {
  private final List<Interceptor> interceptors;
  private final StreamAllocation streamAllocation;
  private final HttpCodec httpCodec;
  private final RealConnection connection;
  private final int index;//鏈節(jié)的角標(biāo)
  private final Request request;//保存Request 
  private final Call call;//保存RealCall 
  private final EventListener eventListener;
  private final int connectTimeout;
  private final int readTimeout;
  private final int writeTimeout;
  private int calls;

  public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
      HttpCodec httpCodec, RealConnection connection, int index, Request request, Call call,
      EventListener eventListener, int connectTimeout, int readTimeout, int writeTimeout) {
    this.interceptors = interceptors;
    this.connection = connection;
    this.streamAllocation = streamAllocation;
    this.httpCodec = httpCodec;
    this.index = index;
    this.request = request;
    this.call = call;
    this.eventListener = eventListener;
    this.connectTimeout = connectTimeout;
    this.readTimeout = readTimeout;
    this.writeTimeout = writeTimeout;
  }

  //調(diào)用4參的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 (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 (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }
    //構(gòu)建下一鏈節(jié),角標(biāo)加1
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    //從列表取出第一個(gè)攔截器
    Interceptor interceptor = interceptors.get(index);
    //調(diào)用intercept超埋,將下一鏈節(jié)傳入
    Response response = interceptor.intercept(next);

    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    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;
  }
}

攔截器鏈的整體結(jié)構(gòu)類似鏈表搏讶,RealInterceptorChain相當(dāng)于鏈表節(jié)點(diǎn)對象,封裝了攔截器霍殴,每個(gè)節(jié)點(diǎn)媒惕,由上一個(gè)節(jié)點(diǎn)構(gòu)造而來。假設(shè)我們沒有自定義自己的攔截器来庭,則第一鏈節(jié)會取出RetryAndFollowUpInterceptor妒蔚,并構(gòu)造下一個(gè)節(jié)點(diǎn)RealInterceptorChain,調(diào)用intercept方法月弛,將節(jié)點(diǎn)傳入肴盏。

//重定向攔截器
public final class RetryAndFollowUpInterceptor implements Interceptor {
  //失敗重連的最大次數(shù)
  private static final int MAX_FOLLOW_UPS = 20;

    
    @Override public Response intercept(Chain chain) throws IOException {
    //從成員變量獲取Request 
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    //從成員變量獲取RealCall 
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();
    //用于服務(wù)端數(shù)據(jù)的傳輸
    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;
    //重連累計(jì)次數(shù)
    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;
      try {
        //調(diào)用proceed,取出第二個(gè)攔截器帽衙,和構(gòu)造第三個(gè)節(jié)點(diǎn)
        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(), streamAllocation, false, request)) {
          throw e.getFirstConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }

      Request followUp;
      try {
        followUp = followUpRequest(response, streamAllocation.route());
      } catch (IOException e) {
        streamAllocation.release();
        throw e;
      }

      if (followUp == null) {
        streamAllocation.release();
        return response;
      }

      closeQuietly(response.body());
      //重連超過20次則斷開連接
      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      if (followUp.body() instanceof UnrepeatableRequestBody) {
        streamAllocation.release();
        throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
      }

      if (!sameConnection(response, followUp.url())) {
        streamAllocation.release();
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
        this.streamAllocation = streamAllocation;
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      request = followUp;
      priorResponse = response;
    }
  }

}

StreamAllocation用于和服務(wù)端數(shù)據(jù)傳輸叁鉴,但在這一個(gè)鏈節(jié)不會用到,會在 ConnectInterceptor這一節(jié)使用到佛寿。
proceed的執(zhí)行類似遞歸幌墓,取出了第二個(gè)攔截器并構(gòu)造了第三個(gè)但壮,就是通過這種方式構(gòu)建整條攔截器鏈,由最后的鏈節(jié)獲得Response 響應(yīng)數(shù)據(jù)常侣,回溯返回蜡饵。這一節(jié)如果失敗了,會進(jìn)行循環(huán)重試胳施,超過最大次數(shù)20次溯祸,則釋放資源。
由攔截器列表添加順序知道舞肆,下一個(gè)攔截器為BridgeInterceptor焦辅。

public final class BridgeInterceptor implements Interceptor {
  private final CookieJar cookieJar;

  public BridgeInterceptor(CookieJar cookieJar) {
    this.cookieJar = cookieJar;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();

    RequestBody body = userRequest.body();
    //添加請求頭信息
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString());
      }

      long contentLength = body.contentLength();
      if (contentLength != -1) {
        requestBuilder.header("Content-Length", Long.toString(contentLength));
        requestBuilder.removeHeader("Transfer-Encoding");
      } else {
        requestBuilder.header("Transfer-Encoding", "chunked");
        requestBuilder.removeHeader("Content-Length");
      }
    }

    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }

    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive");
    }

    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }

    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    }

    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", Version.userAgent());
    }

    //交由下一個(gè)攔截器去做請求
    Response networkResponse = chain.proceed(requestBuilder.build());
    //轉(zhuǎn)化成客戶端可以使用的Response
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);
    //解壓縮包
    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
      GzipSource responseBody = new GzipSource(networkResponse.body().source());
      Headers strippedHeaders = networkResponse.headers().newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build();
      responseBuilder.headers(strippedHeaders);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

  
  private String cookieHeader(List<Cookie> cookies) {
    StringBuilder cookieHeader = new StringBuilder();
    for (int i = 0, size = cookies.size(); i < size; i++) {
      if (i > 0) {
        cookieHeader.append("; ");
      }
      Cookie cookie = cookies.get(i);
      cookieHeader.append(cookie.name()).append('=').append(cookie.value());
    }
    return cookieHeader.toString();
  }
}

BridgeInterceptor 主要是為用戶的Request請求添加請求頭等信息,轉(zhuǎn)化為標(biāo)準(zhǔn)的網(wǎng)絡(luò)請求椿胯。接收到響應(yīng)數(shù)據(jù)后筷登,解壓或解析成客戶端方便使用的數(shù)據(jù)格式。下一請求環(huán)節(jié)將交由CacheInterceptor哩盲。

 OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout( 5, TimeUnit.SECONDS )
                .cache( new Cache( new File( "cache" ),20*1024*1024 ) )//緩存大小
                .build();

在構(gòu)建OkHttpClient 時(shí)前方,我們傳入了Cache對象來做緩存設(shè)置,先來看Cache類的實(shí)現(xiàn)廉油。

//緩存類
public final class Cache implements Closeable, Flushable {
  private static final int VERSION = 201105;
  private static final int ENTRY_METADATA = 0;
  private static final int ENTRY_BODY = 1;
  private static final int ENTRY_COUNT = 2;

  //內(nèi)部類實(shí)現(xiàn)了InternalCache接口惠险,實(shí)際方法都由Cache 類實(shí)現(xiàn)
  final InternalCache internalCache = new InternalCache() {
    @Override public Response get(Request request) throws IOException {
      return Cache.this.get(request);
    }

    @Override public CacheRequest put(Response response) throws IOException {
      return Cache.this.put(response);
    }

    @Override public void remove(Request request) throws IOException {
      Cache.this.remove(request);
    }

    @Override public void update(Response cached, Response network) {
      Cache.this.update(cached, network);
    }

    @Override public void trackConditionalCacheHit() {
      Cache.this.trackConditionalCacheHit();
    }

    @Override public void trackResponse(CacheStrategy cacheStrategy) {
      Cache.this.trackResponse(cacheStrategy);
    }
  };

  //put緩存方法
@Nullable CacheRequest put(Response response) {
    //獲取請求方式
    String requestMethod = response.request().method();
    //如果是"POST""PATCH""PUT""DELETE""MOVE"的請求方式,則不緩存
    if (HttpMethod.invalidatesCache(response.request().method())) {
      try {
        remove(response.request());
      } catch (IOException ignored) {
        // The cache cannot be written.
      }
      return null;
    }
    //只緩存get方式
    if (!requestMethod.equals("GET")) {
         return null;
    }

    if (HttpHeaders.hasVaryAll(response)) {
      return null;
    }

    //實(shí)際用了DiskLruCache緩存
    Entry entry = new Entry(response);
    DiskLruCache.Editor editor = null;
    try {
      editor = cache.edit(key(response.request().url()));
      if (editor == null) {
        return null;
      }
      //緩存請求方式和路徑等
      entry.writeTo(editor);
      //緩存請求body
      return new CacheRequestImpl(editor);
    } catch (IOException e) {
      abortQuietly(editor);
      return null;
    }
  }
   //get獲取緩存內(nèi)容方法
   Response get(Request request) {
    String key = key(request.url());//獲取key
    DiskLruCache.Snapshot snapshot;//緩存快照
    Entry entry;//緩存Entry
    try {
        snapshot = cache.get(key);//通過key獲取緩存快照
        if (snapshot == null) {
        return null;
         }
    } catch (IOException e) {
        return null;
    }
    try {
        entry = new Entry(snapshot.getSource(ENTRY_METADATA));//如果緩存快照存在抒线,那么構(gòu)造Entry
    } catch (IOException e) {
        Util.closeQuietly(snapshot);
        return null;
    }
    Response response = entry.response(snapshot);//通過快緩存照獲取響應(yīng)體
    if (!entry.matches(request, response)) {
        Util.closeQuietly(response.body());
        return null;
    }
        return response;
    }
  }

//緩存內(nèi)部類
private final class CacheRequestImpl implements CacheRequest {
    private final DiskLruCache.Editor editor;
    private Sink cacheOut;
    private Sink body;
    boolean done;

    CacheRequestImpl(final DiskLruCache.Editor editor) {
      this.editor = editor;
      this.cacheOut = editor.newSink(ENTRY_BODY);
      this.body = new ForwardingSink(cacheOut) {
        @Override public void close() throws IOException {
          synchronized (Cache.this) {
            if (done) {
              return;
            }
            done = true;
            writeSuccessCount++;
          }
          super.close();
          editor.commit();
        }
      };
    }

    @Override public void abort() {
      synchronized (Cache.this) {
        if (done) {
          return;
        }
        done = true;
        writeAbortCount++;
      }
      Util.closeQuietly(cacheOut);
      try {
        editor.abort();
      } catch (IOException ignored) {
      }
    }

    @Override public Sink body() {
      return body;
    }
  }
}

InternalCache是一個(gè)接口班巩,定義了緩存的各項(xiàng)操作,Cache 定義了一個(gè)匿名內(nèi)部類來實(shí)現(xiàn)緩存的操作嘶炭。
從緩存put/get方法分析可以看出抱慌,內(nèi)部緩存實(shí)現(xiàn)是DiskLruCache緩存,并且只緩存Get請求方式旱物。
CacheRequestImpl類進(jìn)行了緩存封裝,它實(shí)現(xiàn)了CacheRequest 接口卫袒,用來暴露給緩存攔截器進(jìn)行緩存操作宵呛。

public final class CacheInterceptor implements Interceptor {
  final InternalCache cache;

  public CacheInterceptor(InternalCache cache) {
    this.cache = cache;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    //緩存不為null則從緩存獲取
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();
    //是獲取網(wǎng)絡(luò)還是獲取緩存
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
    //對緩存的名字進(jìn)行次數(shù)累計(jì)
    if (cache != null) {
      cache.trackResponse(strategy);
    }

    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); 
    }

    // 沒有網(wǎng)絡(luò),也沒有緩存夕凝,手動構(gòu)造Response宝穗,返回504
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }

    // 沒有網(wǎng)絡(luò),但有緩存码秉,將緩存數(shù)據(jù)返回
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

    Response networkResponse = null;
    try {
      //交由下一個(gè)環(huán)請求操作
      networkResponse = chain.proceed(networkRequest);
    } finally {
      //關(guān)閉緩存資源
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

    // 有網(wǎng)絡(luò)逮矛,這里再次判斷是否要使用緩存
    if (cacheResponse != null) {
      //狀態(tài)碼304,獲取緩存
      if (networkResponse.code() == HTTP_NOT_MODIFIED) {
        Response 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();

         cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } else {
        closeQuietly(cacheResponse.body());
      }
    }
    //最終沒有緩存转砖,則構(gòu)造網(wǎng)絡(luò)獲取的數(shù)據(jù)返回
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        //將數(shù)據(jù)緩存起來
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }

    return response;
  }

CacheInterceptor 通過獲取緩存和網(wǎng)絡(luò)請求兩種策略進(jìn)行比對须鼎,來決定是采用緩存數(shù)據(jù)還是網(wǎng)絡(luò)數(shù)據(jù)鲸伴,并在最后將數(shù)據(jù)緩存起來,以便下次獲取晋控。
如果當(dāng)前網(wǎng)絡(luò)沒有問題汞窗,下個(gè)攔截器將通過連接復(fù)用的方式,獲取到一個(gè)網(wǎng)絡(luò)連接RealConnection 赡译,以供最后一個(gè)攔截器做網(wǎng)絡(luò)請求仲吏,獲取連接的攔截器為ConnectInterceptor。

public final class ConnectInterceptor implements Interceptor {
  public final OkHttpClient client;

  public ConnectInterceptor(OkHttpClient client) {
    this.client = client;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    //StreamAllocation在RetryAndFollowUpInterceptor中創(chuàng)建
    StreamAllocation streamAllocation = realChain.streamAllocation();
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    //HttpCodec為一個(gè)接口蝌焚,對應(yīng)HttpCodec1和HttpCodec2裹唆,即1.0和2.0,主要用于編碼request和解碼response。并且和服務(wù)端建立了連接
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();
    //傳遞給CallServerInterceptor攔截器
    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }
}
public final class StreamAllocation {
  public final Address address;
  private RouteSelector.Selection routeSelection;
  private Route route;
  private final ConnectionPool connectionPool;//連接池
  public final Call call;
  public final EventListener eventListener;
  private final Object callStackTrace;

  private final RouteSelector routeSelector;
  private int refusedStreamCount;
  private RealConnection connection;
  private boolean reportedAcquired;
  private boolean released;
  private boolean canceled;
  private HttpCodec codec;

  public StreamAllocation(ConnectionPool connectionPool, Address address, Call call,
      EventListener eventListener, Object callStackTrace) {
    this.connectionPool = connectionPool;
    this.address = address;
    this.call = call;
    this.eventListener = eventListener;
    this.routeSelector = new RouteSelector(address, routeDatabase(), call, eventListener);
    this.callStackTrace = callStackTrace;
  }

  public HttpCodec newStream(OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    int connectTimeout = chain.connectTimeoutMillis();
    int readTimeout = chain.readTimeoutMillis();
    int writeTimeout = chain.writeTimeoutMillis();
    int pingIntervalMillis = client.pingIntervalMillis();
    boolean connectionRetryEnabled = client.retryOnConnectionFailure();

    try {
      //獲得連接類只洒,用于網(wǎng)絡(luò)連接
      RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
          writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
      //獲得編解碼器
      HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);

      synchronized (connectionPool) {
        codec = resultCodec;
        return resultCodec;
      }
    } catch (IOException e) {
      throw new RouteException(e);
    }
  }

  //獲取連接器
  private RealConnection findHealthyConnection(int connectTimeout, int readTimeout,
      int writeTimeout, int pingIntervalMillis, boolean connectionRetryEnabled,
      boolean doExtensiveHealthChecks) throws IOException {

    //死循環(huán)查找
    while (true) {
      RealConnection candidate = findConnection(connectTimeout, readTimeout, writeTimeout,
          pingIntervalMillis, connectionRetryEnabled);
      //如果successCount 為0许帐,說明可用,結(jié)束循環(huán)
      synchronized (connectionPool) {
        if (candidate.successCount == 0) {
          return candidate;
        }
      }
      //如果這個(gè)連接無效(比如流沒關(guān)閉)红碑,則回收舞吭,尋找下一個(gè)
      if (!candidate.isHealthy(doExtensiveHealthChecks)) {
        noNewStreams();
        continue;
      }
      return candidate;
    }
  }
}

//獲取一個(gè)RealConnection 鏈接
private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
      int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {

    boolean foundPooledConnection = false;
    RealConnection result = null;
    Route selectedRoute = null;
    Connection releasedConnection;
    Socket toClose;
    synchronized (connectionPool) {
      if (released) throw new IllegalStateException("released");
      if (codec != null) throw new IllegalStateException("codec != null");
      if (canceled) throw new IOException("Canceled");

      //看是否能復(fù)用connection
      releasedConnection = this.connection;
      toClose = releaseIfNoNewStreams();
    
      if (this.connection != null) {
         result = this.connection;
        releasedConnection = null;
      }
      if (!reportedAcquired) {
          releasedConnection = null;
      }

      //不能復(fù)用說明為null,從池里獲取新的
      if (result == null) {
        // 假設(shè)連接池中可用的析珊,第一次嘗試獲取一個(gè)
        Internal.instance.get(connectionPool, address, this, null);
        if (connection != null) {
          foundPooledConnection = true;
          result = connection;
        } else {
          selectedRoute = route;
        }
      }
    }
    closeQuietly(toClose);

    if (releasedConnection != null) {
      eventListener.connectionReleased(call, releasedConnection);
    }
   //foundPooledConnection為true羡鸥,說明第一次嘗試找到了
    if (foundPooledConnection) {
      eventListener.connectionAcquired(call, result);
    }
    //成功獲取則返回
    if (result != null) {
         return result;
    }

    //不能復(fù)用,連接池也沒有忠寻,則下面將獲取一個(gè)新的路由
    boolean newRouteSelection = false;
    if (selectedRoute == null && (routeSelection == null || !routeSelection.hasNext())) {
      newRouteSelection = true;
      routeSelection = routeSelector.next();
    }

    synchronized (connectionPool) {
      if (canceled) throw new IOException("Canceled");

      if (newRouteSelection) {
      //獲取新的路由惧浴,并第二次嘗試從池中獲取
        List<Route> routes = routeSelection.getAll();
        for (int i = 0, size = routes.size(); i < size; i++) {
          Route route = routes.get(i);
          Internal.instance.get(connectionPool, address, this, route);
          if (connection != null) {
            foundPooledConnection = true;
            result = connection;
            this.route = route;
            break;
          }
        }
      }
      //新建一個(gè)鏈接
      if (!foundPooledConnection) {
        if (selectedRoute == null) {
          selectedRoute = routeSelection.next();
        }

        route = selectedRoute;
        refusedStreamCount = 0;
        //構(gòu)建新的RealConnection
        result = new RealConnection(connectionPool, selectedRoute);
        acquire(result, false);
      }
    }

    // foundPooledConnection為true,說明第二次嘗試找到了
    if (foundPooledConnection) {
      eventListener.connectionAcquired(call, result);
      return result;
    }

    // 建立新的連接
    result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
        connectionRetryEnabled, call, eventListener);
    routeDatabase().connected(result.route());

    Socket socket = null;
    synchronized (connectionPool) {
      reportedAcquired = true;

      // 將連接放入池中
      Internal.instance.put(connectionPool, result);

      if (result.isMultiplexed()) {
        socket = Internal.instance.deduplicate(connectionPool, address, this);
        result = connection;
      }
    }
    closeQuietly(socket);

    eventListener.connectionAcquired(call, result);
    return result;
  }

findConnection獲取一個(gè)鏈接做了多次嘗試奕剃,如下:
1衷旅,先判斷了當(dāng)前的連接是否能復(fù)用,能復(fù)用則返回纵朋;
2柿顶,不能復(fù)用,第一次嘗試從連接池獲取操软,獲取到了則返回嘁锯;
3,第一次連接池獲取失敗聂薪,取下一個(gè)路由家乘,并第二次嘗試從連接池獲取,獲取到則返回藏澳;
4仁锯,第二次嘗試獲取失敗,則新建一個(gè)鏈接翔悠,并把連接緩存到連接池中业崖。

下面來看下是如何從ConnectionPool 連接池中獲取到一個(gè)鏈接野芒,和一個(gè)新鏈接如何緩存到池中的。

public final class ConnectionPool {
  //線程池
  private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
      Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
      new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));

  //
  private final int maxIdleConnections;
  private final long keepAliveDurationNs;
  //緩存隊(duì)列
  private final Deque<RealConnection> connections = new ArrayDeque<>();
  
  //從池里獲取連接
 @Nullable RealConnection get(Address address, StreamAllocation streamAllocation, Route route) {
    assert (Thread.holdsLock(this));
    //遍歷隊(duì)列判斷是否符合條件
    for (RealConnection connection : connections) {
      //根據(jù)地址和路由判斷是否可用
      if (connection.isEligible(address, route)) {
        //如果符合則
        streamAllocation.acquire(connection, true);
        return connection;
      }
    }
    return null;
  }
public final class StreamAllocation {
    //保存當(dāng)前獲取到的connection
    private RealConnection connection;
        
    public void acquire(RealConnection connection, boolean reportedAcquired) {
        assert (Thread.holdsLock(connectionPool));
        if (this.connection != null) throw new IllegalStateException();
        //將符合條件的connection賦值給成員變量
        this.connection = connection;
        this.reportedAcquired = reportedAcquired;
        //將當(dāng)前StreamAllocation 添加到RealConnection 的弱引用列表中
        connection.allocations.add(new StreamAllocationReference(this, callStackTrace));
    }
}

public final class RealConnection extends Http2Connection.Listener implements Connection {
  //弱引用列表
  public final List<Reference<StreamAllocation>> allocations = new ArrayList<>();

連接池get方法腻要,是通過遍歷緩存隊(duì)列ArrayDeque复罐,根據(jù)地址和路由,判斷是否有可用的連接雄家,如果找到了效诅,則調(diào)用StreamAllocation 的acquire方法,將connection 保存到成員變量中趟济,同時(shí)將當(dāng)前的StreamAllocation 對象封裝成弱引用乱投,加入到RealConnection 的成員列表allocations 中。這個(gè)列表的個(gè)數(shù)就是用來判斷我們的最大連接數(shù)是否超過64個(gè)的顷编。

下面看連接池如何緩存新建的RealConnection戚炫,即put方法:

public final class ConnectionPool {
  //線程池
  private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
      Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
      new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));

  //
  private final int maxIdleConnections;
  private final long keepAliveDurationNs;
  //緩存隊(duì)列
  private final Deque<RealConnection> connections = new ArrayDeque<>();

//緩存RealConnection 
  void put(RealConnection connection) {
    assert (Thread.holdsLock(this));
    //標(biāo)記清除算法來回收RealConnection 
    if (!cleanupRunning) {
      cleanupRunning = true;
      executor.execute(cleanupRunnable);
    }
    //將新的RealConnection 添加到隊(duì)列中
    connections.add(connection);
    }
  }

  //回收線程
  private final Runnable cleanupRunnable = new Runnable() {
    @Override public void run() {
      while (true) {
        //與下一次需要清理的間隔時(shí)間,cleanup做清除
        long waitNanos = cleanup(System.nanoTime());
        if (waitNanos == -1) return;
        if (waitNanos > 0) {
          long waitMillis = waitNanos / 1000000L;
          waitNanos -= (waitMillis * 1000000L);
          synchronized (ConnectionPool.this) {
            try {
              //等待waitNanos后再次做清除
              ConnectionPool.this.wait(waitMillis, (int) waitNanos);
            } catch (InterruptedException ignored) {
            }
          }
        }
      }
    }
  };

 //實(shí)際做回收的方法
 long cleanup(long now) {
    //記錄活躍的連接數(shù)
    int inUseConnectionCount = 0;
    //記錄空閑的連接數(shù)
    int idleConnectionCount = 0;
    //空閑時(shí)間最長的連接
    RealConnection longestIdleConnection = null;
    long longestIdleDurationNs = Long.MIN_VALUE;

    // 遍歷隊(duì)列
    synchronized (this) {
      for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {
        RealConnection connection = i.next();

        // 返回0說明連接正在使用媳纬,則inUseConnectionCount加1双肤,獲取下一個(gè)連接
        if (pruneAndGetAllocationCount(connection, now) > 0) {
          inUseConnectionCount++;
          continue;
        }
        //說明空閑,空閑連接加1
        idleConnectionCount++;

        // 找出了空閑時(shí)間最長的連接钮惠,準(zhǔn)備移除
        long idleDurationNs = now - connection.idleAtNanos;
        if (idleDurationNs > longestIdleDurationNs) {
          longestIdleDurationNs = idleDurationNs;
          longestIdleConnection = connection;
        }
      }
      //如果空閑時(shí)間最長的連接的空閑時(shí)間超過了5分鐘茅糜,或是空閑的連接數(shù)超過了限制,就移除
      if (longestIdleDurationNs >= this.keepAliveDurationNs
          || idleConnectionCount > this.maxIdleConnections) {
        //從隊(duì)列移除
        connections.remove(longestIdleConnection);
      } else if (idleConnectionCount > 0) {
        //如果存在空閑連接但是還沒有超過5分鐘素挽,就返回剩下的時(shí)間蔑赘,便于下次進(jìn)行清理
        return keepAliveDurationNs - longestIdleDurationNs;
      } else if (inUseConnectionCount > 0) {
        // 如果沒有空閑的連接,那就等5分鐘后再嘗試清理
        return keepAliveDurationNs;
      } else {
        // 當(dāng)前沒有任何連接预明,就返回-1缩赛,跳出循環(huán)
        cleanupRunning = false;
        return -1;
      }
    }

    closeQuietly(longestIdleConnection.socket());
    return 0;
  }


  //判斷當(dāng)前連接是否正在使用
private int pruneAndGetAllocationCount(RealConnection connection, long now) {
    //獲取軟引用列表
    List<Reference<StreamAllocation>> references = connection.allocations;
    //遍歷
    for (int i = 0; i < references.size(); ) {
      Reference<StreamAllocation> reference = references.get(i);
     //如果存在引用,就說明是活躍連接撰糠,就繼續(xù)看下一個(gè)StreamAllocation
      if (reference.get() != null) {
        i++;
        continue;
      }

      
      StreamAllocation.StreamAllocationReference streamAllocRef =
          (StreamAllocation.StreamAllocationReference) reference;
      String message = "A connection to " + connection.route().address().url()
          + " was leaked. Did you forget to close a response body?";
      Platform.get().logCloseableLeak(message, streamAllocRef.callStackTrace);

    //如果沒有引用酥馍,就移除
      references.remove(i);
      connection.noNewStreams = true;

      // 如果列表為空,就說明此連接上沒有StreamAllocation引用了阅酪,就返回0旨袒,表示是空閑的連接
      if (references.isEmpty()) {
        connection.idleAtNanos = now - keepAliveDurationNs;
        return 0;
      }
    }
    //遍歷結(jié)束后,返回引用的數(shù)量遮斥,說明當(dāng)前連接是活躍連接
    return references.size();
  }
}
 

Ok中支持5個(gè)并發(fā)socket連接峦失,默認(rèn)的keepAlive時(shí)間為5分鐘扇丛,也可以在構(gòu)建OkHttpClient時(shí)設(shè)置术吗。向連接池添加新的連接前,會線程池來清理空閑的連接较屿。其本質(zhì)是判斷每個(gè)連接的引用計(jì)數(shù)對象StreamAllocation的計(jì)數(shù)隧魄,來回收空閑的連接的。

ConnectInterceptor 攔截器的主要任務(wù)就是配合ConnectionPool 連接池隘蝎,獲取到一個(gè)RealConnection 购啄,并生成編解碼器HttpCodec,傳遞給下一個(gè)攔截器CallServerInterceptor進(jìn)行網(wǎng)絡(luò)請求嘱么。

public final class CallServerInterceptor implements Interceptor {
  private final boolean forWebSocket;

  public CallServerInterceptor(boolean forWebSocket) {
    this.forWebSocket = forWebSocket;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    HttpCodec httpCodec = realChain.httpStream();
    StreamAllocation streamAllocation = realChain.streamAllocation();
    RealConnection connection = (RealConnection) realChain.connection();
    Request request = realChain.request();
    //發(fā)送請求的時(shí)間戳
    long sentRequestMillis = System.currentTimeMillis();

    realChain.eventListener().requestHeadersStart(realChain.call());
    //向socket寫入頭信息
    httpCodec.writeRequestHeaders(request);
    realChain.eventListener().requestHeadersEnd(realChain.call(), request);

    Response.Builder responseBuilder = null;
     //如果有body狮含,則向socket寫入body信息
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      
      if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
        httpCodec.flushRequest();
        realChain.eventListener().responseHeadersStart(realChain.call());
        responseBuilder = httpCodec.readResponseHeaders(true);
      }

   
      if (responseBuilder == null) {

        realChain.eventListener().requestBodyStart(realChain.call());
        long contentLength = request.body().contentLength();
        CountingSink requestBodyOut =
            new CountingSink(httpCodec.createRequestBody(request, contentLength));
        BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);

        request.body().writeTo(bufferedRequestBody);
        bufferedRequestBody.close();
        realChain.eventListener()
            .requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
      } else if (!connection.isMultiplexed()) {
        
        streamAllocation.noNewStreams();
      }
    }
    //完成寫入操作
    httpCodec.finishRequest();

    if (responseBuilder == null) {
      realChain.eventListener().responseHeadersStart(realChain.call());
      //httpCodec解碼讀取返回的數(shù)據(jù),返回responseBuilder 構(gòu)建者
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

    //responseBuilder 構(gòu)建Response 
    Response response = responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();

    ......

   //返回response
    return response;
  }
  

CallServerInterceptor 主要任務(wù)是曼振,向Socket中寫入請求信息几迄,并讀取返回的數(shù)據(jù)。再將Response一層層向前返回冰评,最終返回到RealCall的getResponseWithInterceptorChain方法映胁。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市甲雅,隨后出現(xiàn)的幾起案子解孙,更是在濱河造成了極大的恐慌,老刑警劉巖抛人,帶你破解...
    沈念sama閱讀 210,914評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件弛姜,死亡現(xiàn)場離奇詭異,居然都是意外死亡函匕,警方通過查閱死者的電腦和手機(jī)娱据,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,935評論 2 383
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來盅惜,“玉大人中剩,你說我怎么就攤上這事∈慵牛” “怎么了结啼?”我有些...
    開封第一講書人閱讀 156,531評論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長屈芜。 經(jīng)常有香客問我郊愧,道長井佑,這世上最難降的妖魔是什么属铁? 我笑而不...
    開封第一講書人閱讀 56,309評論 1 282
  • 正文 為了忘掉前任,我火速辦了婚禮躬翁,結(jié)果婚禮上焦蘑,老公的妹妹穿的比我還像新娘。我一直安慰自己盒发,他們只是感情好例嘱,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,381評論 5 384
  • 文/花漫 我一把揭開白布狡逢。 她就那樣靜靜地躺著,像睡著了一般拼卵。 火紅的嫁衣襯著肌膚如雪奢浑。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,730評論 1 289
  • 那天腋腮,我揣著相機(jī)與錄音雀彼,去河邊找鬼。 笑死即寡,一個(gè)胖子當(dāng)著我的面吹牛详羡,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播嘿悬,決...
    沈念sama閱讀 38,882評論 3 404
  • 文/蒼蘭香墨 我猛地睜開眼实柠,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了善涨?” 一聲冷哼從身側(cè)響起窒盐,我...
    開封第一講書人閱讀 37,643評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎钢拧,沒想到半個(gè)月后蟹漓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,095評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡源内,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,448評論 2 325
  • 正文 我和宋清朗相戀三年葡粒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片膜钓。...
    茶點(diǎn)故事閱讀 38,566評論 1 339
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡嗽交,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出颂斜,到底是詐尸還是另有隱情夫壁,我是刑警寧澤,帶...
    沈念sama閱讀 34,253評論 4 328
  • 正文 年R本政府宣布沃疮,位于F島的核電站盒让,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏司蔬。R本人自食惡果不足惜邑茄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,829評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望俊啼。 院中可真熱鬧肺缕,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,715評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽豪墅。三九已至泉手,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間偶器,已是汗流浹背斩萌。 一陣腳步聲響...
    開封第一講書人閱讀 31,945評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留屏轰,地道東北人颊郎。 一個(gè)月前我還...
    沈念sama閱讀 46,248評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像霎苗,于是被迫代替她去往敵國和親姆吭。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,440評論 2 348

推薦閱讀更多精彩內(nèi)容

  • Okhttp 基礎(chǔ)知識導(dǎo)圖 Okhttp 使用1唁盏,創(chuàng)建一個(gè)客戶端内狸。2,創(chuàng)建一個(gè)請求厘擂。3昆淡,發(fā)起請求(入?yún)⒒卣{(diào))。 一...
    gczxbb閱讀 2,054評論 0 2
  • 本文為本人原創(chuàng)刽严,轉(zhuǎn)載請注明作者和出處昂灵。 在上一章我們分析了Okhttp分發(fā)器對同步/異步請求的處理,本章將和大家一...
    業(yè)松閱讀 966評論 2 8
  • 2.okhttp3.0整體流程:1).創(chuàng)建okhttpclient客戶端對象舞萄,表示所有的http請求的客戶端的類眨补,...
    無為3閱讀 369評論 0 1
  • OkHttp優(yōu)點(diǎn) OkHttp是一個(gè)高效的Http客戶端,有如下的特點(diǎn): 支持HTTP2/SPDY黑科技 sock...
    礪雪凝霜閱讀 16,196評論 5 47
  • 七月正是采摘花椒的季節(jié)倒脓,手抓式渤涌、拔河式、仰望式把还、俯瞰式实蓬、勒索式…姿態(tài)萬千的勞動場景在我們這條山溝里一一呈現(xiàn)在來來回...
    海參崴的酒閱讀 201評論 0 1