美文网首页
OkHttp源码(二)

OkHttp源码(二)

作者: JackyWu15 | 来源:发表于2019-12-24 15:39 被阅读0次

由上篇分析了Ok请求的执行流程知道,无论是同步还是异步,最终得到网络响应,都是通过调用getResponseWithInterceptorChain() 来获取的,其内部实现了一条拦截器链。下面开始分析源码内部的5个拦截器的调用,以及网络数据的请求流程。

final class RealCall implements Call {
  //构造一条拦截器链
  Response getResponseWithInterceptorChain() throws IOException {
    // 构建一个列表来存放所有的拦截器
    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);
  }

用户可以自定义自己的拦截器,并被首先添加到列表中,系统内部自己实现了5个重要的拦截器,分别是RetryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor和CallServerInterceptor,整个拦截器链正是通过这5个拦截器串联起来的。我们首先看proceed方法,它接收了我们构造的Request对象。

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

  interface Chain {
    Request request();

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

Interceptor 是拦截器的接口,由子类实现不同拦截器。Chain 是其内部类,它由RealInterceptorChain,构成链的节点。

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;//链节的角标
  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;
  }

  //调用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");
    }
    //构建下一链节,角标加1
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    //从列表取出第一个拦截器
    Interceptor interceptor = interceptors.get(index);
    //调用intercept,将下一链节传入
    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;
  }
}

拦截器链的整体结构类似链表,RealInterceptorChain相当于链表节点对象,封装了拦截器,每个节点,由上一个节点构造而来。假设我们没有自定义自己的拦截器,则第一链节会取出RetryAndFollowUpInterceptor,并构造下一个节点RealInterceptorChain,调用intercept方法,将节点传入。

//重定向拦截器
public final class RetryAndFollowUpInterceptor implements Interceptor {
  //失败重连的最大次数
  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();
    //用于服务端数据的传输
    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;
    //重连累计次数
    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;
      try {
        //调用proceed,取出第二个拦截器,和构造第三个节点
        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用于和服务端数据传输,但在这一个链节不会用到,会在 ConnectInterceptor这一节使用到。
proceed的执行类似递归,取出了第二个拦截器并构造了第三个,就是通过这种方式构建整条拦截器链,由最后的链节获得Response 响应数据,回溯返回。这一节如果失败了,会进行循环重试,超过最大次数20次,则释放资源。
由拦截器列表添加顺序知道,下一个拦截器为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());
    }

    //交由下一个拦截器去做请求
    Response networkResponse = chain.proceed(requestBuilder.build());
    //转化成客户端可以使用的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请求添加请求头等信息,转化为标准的网络请求。接收到响应数据后,解压或解析成客户端方便使用的数据格式。下一请求环节将交由CacheInterceptor。

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

在构建OkHttpClient 时,我们传入了Cache对象来做缓存设置,先来看Cache类的实现。

//缓存类
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;

  //内部类实现了InternalCache接口,实际方法都由Cache 类实现
  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;
    }

    //实际用了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获取缓存内容方法
   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));//如果缓存快照存在,那么构造Entry
    } catch (IOException e) {
        Util.closeQuietly(snapshot);
        return null;
    }
    Response response = entry.response(snapshot);//通过快缓存照获取响应体
    if (!entry.matches(request, response)) {
        Util.closeQuietly(response.body());
        return null;
    }
        return response;
    }
  }

//缓存内部类
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是一个接口,定义了缓存的各项操作,Cache 定义了一个匿名内部类来实现缓存的操作。
从缓存put/get方法分析可以看出,内部缓存实现是DiskLruCache缓存,并且只缓存Get请求方式。
CacheRequestImpl类进行了缓存封装,它实现了CacheRequest 接口,用来暴露给缓存拦截器进行缓存操作。

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();
    //是获取网络还是获取缓存
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
    //对缓存的名字进行次数累计
    if (cache != null) {
      cache.trackResponse(strategy);
    }

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

    // 没有网络,也没有缓存,手动构造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();
    }

    // 没有网络,但有缓存,将缓存数据返回
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

    Response networkResponse = null;
    try {
      //交由下一个环请求操作
      networkResponse = chain.proceed(networkRequest);
    } finally {
      //关闭缓存资源
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

    // 有网络,这里再次判断是否要使用缓存
    if (cacheResponse != null) {
      //状态码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());
      }
    }
    //最终没有缓存,则构造网络获取的数据返回
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        //将数据缓存起来
        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 通过获取缓存和网络请求两种策略进行比对,来决定是采用缓存数据还是网络数据,并在最后将数据缓存起来,以便下次获取。
如果当前网络没有问题,下个拦截器将通过连接复用的方式,获取到一个网络连接RealConnection ,以供最后一个拦截器做网络请求,获取连接的拦截器为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中创建
    StreamAllocation streamAllocation = realChain.streamAllocation();
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    //HttpCodec为一个接口,对应HttpCodec1和HttpCodec2,即1.0和2.0,主要用于编码request和解码response。并且和服务端建立了连接
    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 {
      //获得连接类,用于网络连接
      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 {

    //死循环查找
    while (true) {
      RealConnection candidate = findConnection(connectTimeout, readTimeout, writeTimeout,
          pingIntervalMillis, connectionRetryEnabled);
      //如果successCount 为0,说明可用,结束循环
      synchronized (connectionPool) {
        if (candidate.successCount == 0) {
          return candidate;
        }
      }
      //如果这个连接无效(比如流没关闭),则回收,寻找下一个
      if (!candidate.isHealthy(doExtensiveHealthChecks)) {
        noNewStreams();
        continue;
      }
      return candidate;
    }
  }
}

//获取一个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");

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

      //不能复用说明为null,从池里获取新的
      if (result == null) {
        // 假设连接池中可用的,第一次尝试获取一个
        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;
    }

    //不能复用,连接池也没有,则下面将获取一个新的路由
    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;
          }
        }
      }
      //新建一个链接
      if (!foundPooledConnection) {
        if (selectedRoute == null) {
          selectedRoute = routeSelection.next();
        }

        route = selectedRoute;
        refusedStreamCount = 0;
        //构建新的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获取一个链接做了多次尝试,如下:
1,先判断了当前的连接是否能复用,能复用则返回;
2,不能复用,第一次尝试从连接池获取,获取到了则返回;
3,第一次连接池获取失败,取下一个路由,并第二次尝试从连接池获取,获取到则返回;
4,第二次尝试获取失败,则新建一个链接,并把连接缓存到连接池中。

下面来看下是如何从ConnectionPool 连接池中获取到一个链接,和一个新链接如何缓存到池中的。

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;
  //缓存队列
  private final Deque<RealConnection> connections = new ArrayDeque<>();
  
  //从池里获取连接
 @Nullable RealConnection get(Address address, StreamAllocation streamAllocation, Route route) {
    assert (Thread.holdsLock(this));
    //遍历队列判断是否符合条件
    for (RealConnection connection : connections) {
      //根据地址和路由判断是否可用
      if (connection.isEligible(address, route)) {
        //如果符合则
        streamAllocation.acquire(connection, true);
        return connection;
      }
    }
    return null;
  }
public final class StreamAllocation {
    //保存当前获取到的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;
        //将当前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方法,是通过遍历缓存队列ArrayDeque,根据地址和路由,判断是否有可用的连接,如果找到了,则调用StreamAllocation 的acquire方法,将connection 保存到成员变量中,同时将当前的StreamAllocation 对象封装成弱引用,加入到RealConnection 的成员列表allocations 中。这个列表的个数就是用来判断我们的最大连接数是否超过64个的。

下面看连接池如何缓存新建的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;
  //缓存队列
  private final Deque<RealConnection> connections = new ArrayDeque<>();

//缓存RealConnection 
  void put(RealConnection connection) {
    assert (Thread.holdsLock(this));
    //标记清除算法来回收RealConnection 
    if (!cleanupRunning) {
      cleanupRunning = true;
      executor.execute(cleanupRunnable);
    }
    //将新的RealConnection 添加到队列中
    connections.add(connection);
    }
  }

  //回收线程
  private final Runnable cleanupRunnable = new Runnable() {
    @Override public void run() {
      while (true) {
        //与下一次需要清理的间隔时间,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) {
            }
          }
        }
      }
    }
  };

 //实际做回收的方法
 long cleanup(long now) {
    //记录活跃的连接数
    int inUseConnectionCount = 0;
    //记录空闲的连接数
    int idleConnectionCount = 0;
    //空闲时间最长的连接
    RealConnection longestIdleConnection = null;
    long longestIdleDurationNs = Long.MIN_VALUE;

    // 遍历队列
    synchronized (this) {
      for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {
        RealConnection connection = i.next();

        // 返回0说明连接正在使用,则inUseConnectionCount加1,获取下一个连接
        if (pruneAndGetAllocationCount(connection, now) > 0) {
          inUseConnectionCount++;
          continue;
        }
        //说明空闲,空闲连接加1
        idleConnectionCount++;

        // 找出了空闲时间最长的连接,准备移除
        long idleDurationNs = now - connection.idleAtNanos;
        if (idleDurationNs > longestIdleDurationNs) {
          longestIdleDurationNs = idleDurationNs;
          longestIdleConnection = connection;
        }
      }
      //如果空闲时间最长的连接的空闲时间超过了5分钟,或是空闲的连接数超过了限制,就移除
      if (longestIdleDurationNs >= this.keepAliveDurationNs
          || idleConnectionCount > this.maxIdleConnections) {
        //从队列移除
        connections.remove(longestIdleConnection);
      } else if (idleConnectionCount > 0) {
        //如果存在空闲连接但是还没有超过5分钟,就返回剩下的时间,便于下次进行清理
        return keepAliveDurationNs - longestIdleDurationNs;
      } else if (inUseConnectionCount > 0) {
        // 如果没有空闲的连接,那就等5分钟后再尝试清理
        return keepAliveDurationNs;
      } else {
        // 当前没有任何连接,就返回-1,跳出循环
        cleanupRunning = false;
        return -1;
      }
    }

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


  //判断当前连接是否正在使用
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);
     //如果存在引用,就说明是活跃连接,就继续看下一个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;
      }
    }
    //遍历结束后,返回引用的数量,说明当前连接是活跃连接
    return references.size();
  }
}
 

Ok中支持5个并发socket连接,默认的keepAlive时间为5分钟,也可以在构建OkHttpClient时设置。向连接池添加新的连接前,会线程池来清理空闲的连接。其本质是判断每个连接的引用计数对象StreamAllocation的计数,来回收空闲的连接的。

ConnectInterceptor 拦截器的主要任务就是配合ConnectionPool 连接池,获取到一个RealConnection ,并生成编解码器HttpCodec,传递给下一个拦截器CallServerInterceptor进行网络请求。

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();
    //发送请求的时间戳
    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解码读取返回的数据,返回responseBuilder 构建者
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

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

    ......

   //返回response
    return response;
  }
  

CallServerInterceptor 主要任务是,向Socket中写入请求信息,并读取返回的数据。再将Response一层层向前返回,最终返回到RealCall的getResponseWithInterceptorChain方法。

相关文章

网友评论

      本文标题:OkHttp源码(二)

      本文链接:https://www.haomeiwen.com/subject/fwaznctx.html