美文网首页javaAndroid篇
OkHttp源码分析:分发器和拦截器

OkHttp源码分析:分发器和拦截器

作者: w达不溜w | 来源:发表于2021-03-23 11:51 被阅读0次
    0.调用流程:

    主要分析异步请求

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
      .url(url).build();
    //创建一个RealCall实例
    Call call=okHttpClient.newCall(request);
    //RealCall.enqueue实际就是将一个RealCall放入到任务队列中,等待合适的机会执行
    call.enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
    
      }
    
      @Override
      public void onResponse(Call call, Response response) throws IOException {
        //response.body().string()只能调用一次
        String result=response.body().string();
      }
    });
    
    okhttp.png
    1.分发器

    内部维护队列和线程池,完成请求调配

      call.enqueue
    —>RealCall#enqueue
    —>Dispatcher#enqueue
    
    //异步请求等待执行队列
    private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
    //异步请求正在执行队列
    private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
    //同步请求正在执行队列
    private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
    
    synchronized void enqueue(AsyncCall call) {
      //1.正在执行的请求<64   2.相同host的请求<5
      if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
        runningAsyncCalls.add(call);
        //把任务交给线程池执行
        executorService().execute(call);
      } else {
        readyAsyncCalls.add(call);
      }
    }
    

    正在执行的请求<64并且相同host的请求<5放running,否则放ready
    AsyncCall继承NamedRunnable,NamedRunnable实现了Runnable,NamedRunnable中run()又调用了execute,子类AsyncCall中的execute会被执行:

    @Override protected void execute() {
          boolean signalledCallback = false;
          try {
            //执行请求(拦截器后面分析)
            Response response = getResponseWithInterceptorChain();
            //...
          } catch (IOException e) {
           //...
          } finally {
            //进入finally表示这个请求任务完成
            //调用分发器的finished方法
            client.dispatcher().finished(this);
          }
        }
    

    我们先直接看finally中的client.dispatcher().finished(this)

    //Dispatcher.java
    void finished(AsyncCall call) {
        finished(runningAsyncCalls, call, true);
    }
    
      private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
        int runningCallsCount;
        Runnable idleCallback;
        synchronized (this) {
          //call执行完了,从runningAsyncCalls队列中移除
          if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
          //上面promoteCalls传入true,进入promoteCalls方法
          if (promoteCalls) promoteCalls();
          runningCallsCount = runningCallsCount();
          idleCallback = this.idleCallback;
        }
    
        if (runningCallsCount == 0 && idleCallback != null) {
          idleCallback.run();
        }
      }
    
    //从readyAsyncCalls获取任务放入runningAsyncCalls队列中执行
    private void promoteCalls() {
      //runningAsyncCalls最大容量已满
      if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
      //readyAsyncCalls为空
      if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.
    
      for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
        //①从readyAsyncCalls中取出请求任务
        AsyncCall call = i.next();
                //同host请求最多只能同时5个
        if (runningCallsForHost(call) < maxRequestsPerHost) {
          //②将取出的任务从readyAsyncCalls中移除
          i.remove();
          //③将取出的任务添加到runningAsyncCalls中
          runningAsyncCalls.add(call);
          //④让线程池去执行
          executorService().execute(call);
        }
    
        if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
      }
    }
    
    okhttp分发流程.png

    接着我们看下线程池

    public synchronized ExecutorService executorService() {
        if (executorService == null) {
          //核心线程数,最大线程数,线程最大闲置时间,时间单位,线程等待队列,线程创建工厂
          executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
              new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
        }
        return executorService;
      }
    

    当一个任务通过execute(Runable)方法添加到线程池时:

    • 线程数量<corePoolSize,新建线程(核心)来处理被添加的任务;
    • 线程数量>=corePoolSize,新任务会被添加到等待队列,添加成功则等待空闲线程,添加失败:①线程数量<maximumPoolSize,新建任务执行新任务;②线程数量>maximumPoolSize,拒绝此服务

    OkHttp里面的线程池核心线程数为0,最大线程数为Integer.MAX_VALUE,无容量队列SynchronousQueue设计的目的:分发器线程池无等待,最大并发。

    2.拦截器

    五大拦截器完成整个请求过程

    Response response = getResponseWithInterceptorChain();
    
    //RealCall.java
    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));
        //链条对象Chain
      Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
          originalRequest, this, eventListener, client.connectTimeoutMillis(),
          client.readTimeoutMillis(), client.writeTimeoutMillis());
        //执行下一个拦截器
      return chain.proceed(originalRequest);
    }
    

    简单介绍下五大拦截器:
    1.RetryAndFollowUpInterceptor
    重试拦截器:在交出(交给下一个拦截器)之前,负责判断用户是否取消了请求;在获得了结果之后,会根据响应码判断是否需要重定向(30x),处理方式是:从头部的Location中取处url地址,生成一个新的请求交给下一级(相当于重新发起一次请求)。

    2.BridgeInterceptor
    桥接拦截器:负责将HTTP协议必备的请求头加入其中(如HOST、Content-Type),并添加一些默认的行为(如GZIP压缩);在获得结果后,调用Cookie接口并解析GZIP数据。

    3.CacheInterceptor
    缓存拦截器:在交出前,读取并判断是否使用缓存;获得结果后判断是否缓存。

    4.ConnectInterceptor
    连接拦截器:在交出前,负责找到或新建一个连接,并获取对应的socket流。

    5.CallServerInterceptor
    请求服务器拦截器:真正与服务器进行通信,向服务器发送数据,解析读取响应数据。

    interceptor.png

    责任链模式 —> Request请求,经过5个拦截器,发送到最下边返回响应Response,再发送到最上边。

    五大拦截器详解:https://www.jianshu.com/p/8fd0e3031ebe

    相关文章

      网友评论

        本文标题:OkHttp源码分析:分发器和拦截器

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