OkHttp源码分析

本篇只是听视频课的记录,写得比较乱。

一,基本流程

(1)创建OkHttpClient,Builder模式

(2)创建Request对象,Builder模式

(3)Request封装为Call对象,Call是接口,具体实现是RealCall,此处涉及到RetryAndFollowupInterceptor

(4)用Call执行同步或异步调用。

4.1 RealCall#execute方法

@Override public Response execute() throws IOException {
    synchronized (this) {
      //只能执行一次
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    //获取调用堆栈
    captureCallStackTrace();
    try {
      //调度器,通过exe方法把这个call添加到队列中
      client.dispatcher().executed(this);
      //拦截器
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } finally {
      client.dispatcher().finished(this);
    }
  }

/** 
  Ready async calls in the order they'll be run.
  private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();

  Running asynchronous calls. Includes canceled calls that haven't finished yet.
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

  Running synchronous calls. Includes canceled calls that haven't finished yet. 
  private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
*/

4.2 RealCall#enqueue方法

@Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
}

4.3 Dispatcher#execute方法

/** Used by {@code Call#execute} to signal it is in-flight. */
  synchronized void executed(RealCall call) {
    runningSyncCalls.add(call);
  }

4.4 Dispatcher#enqueue方法

synchronized void enqueue(AsyncCall call) {
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
      //加入正在运行的队列
      runningAsyncCalls.add(call);
      //线程池执行runnable
      executorService().execute(call);
    } else {
      //加入正在等待的队列
      readyAsyncCalls.add(call);
    }
  }

4.5 AsyncCall#execute方法

@Override protected void execute() {
      boolean signalledCallback = false;
      try {
        Response response = getResponseWithInterceptorChain();
        //重定向和重试拦截器
        if (retryAndFollowUpInterceptor.isCanceled()) {
          signalledCallback = true;
          responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
        } else {
          signalledCallback = true;
          responseCallback.onResponse(RealCall.this, response);
        }
      } catch (IOException e) {
        if (signalledCallback) {
          // Do not signal the callback twice!
          Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
        } else {
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        client.dispatcher().finished(this);
      }
    }

二,Dispatcher

维护请求状态,并维护一个线程池用于执行请求。

为什么需要两个队列?

可以理解为Dispatcher为生产者,ExecutorService为消费者

Deque<readyAsyncCalls>缓存

Deque<runningAsyncCalls>正在运行的任务

Call执行完之后需要在runningAsyncCalls队列中移除这个线程,那么readyAsyncCalls队列中的线程在什么时候才会被执行呢?

private void promoteCalls() {
    if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
    if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.

    for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
      AsyncCall call = i.next();

      if (runningCallsForHost(call) < maxRequestsPerHost) {
        i.remove();
        runningAsyncCalls.add(call);
        executorService().execute(call);
      }

      if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
    }
  }

四,拦截器

实现网络监听,请求和相应重写,请求失败重试。

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);
    return chain.proceed(originalRequest);
  }

1. 创建一些列拦截器,并将其放入一个拦截器list中

2. 创建一个拦截器链RealInterceptorChain,并执行拦截器链的proceed方法

3. 在发起请求前对request进行处理(如添加头部)

4. 调用下一个拦截器,获取response

5. 对response进行处理,返回给上一个拦截器

 

4.1 RetryAndFollowUpInterceptor

1. 创建StreamAllocation对象

2. 调用RealInterceptorChain.proceed(...)进行网络请求

3. 根据异常结果或者响应结果判断是否要进行重新请求

4. 调用下一个拦截器,对response进行处理,返回给上一个拦截器

4.2 BridgeInterceptor

1. 负责将用户构建的一个Request转化为能够进行网络访问的请求

2. 将这个符合网络请求的Request进行网络请求

3. 将网络请求回来的相应Response转化为用户可用的Response

4.3 CacheInterceptor

4.4 ConnectInterceptor

1. ConnectInterceptor获取Interceptor传过来的StreamAllocation, streamAllocation.newStream()

2. 将创建好的用于网络IO的RealConnection对象以及与服务器交互最为关键的HttpCodec等对象传递给后面的拦截器

3. 两种连接方式:tunnel, socket

4. 连接池 (1. 产生一个StreamAllocation对象;2. StreamAllocation对象的弱引用添加到RealConnection对象的allocations集合;3. 从连接池中获取)

4.5 CallServerInterceptor

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值