OKHttp 3.10源码解析(一):任务请求

本文详细解析OKHttp 3.10的源码,重点探讨同步与异步任务请求的执行流程。同步任务通过Dispatcher的execute方法直接获取响应,而异步任务通过enqueue方法加入队列,由Dispatcher控制并发执行。Dispatcher利用无缓冲阻塞队列SynchronousQueue和线程池实现高效任务调度,同时限制最大并发数和单一Host并发数。任务执行依赖拦截器链策略,下篇将分析拦截器链的实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OKhttp是目前Android端最热门的网络请求框架之一,它以高效的优点赢得了广大开发者的喜爱,以下是OKhttp的主要特点:

1.支持HTTPS/HTTP2/WebSocket

2.内部维护线程池队列,提高并发访问的效率

3.内部维护连接池,支持多路复用,减少连接创建开销

4.透明的GZIP处理降低了下载数据的大小

5.提供拦截器链(InterceptorChain),实现request与response的分层处理

本篇文章从OKhttp的任务请求开始,来探索框架的内部机制,先来看一个OKhttp的使用例子

        //同步请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
        .url("http://myproject.com/helloworld.txt")
        .build();
        Response response = client.newCall(request).execute();

        //异步请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://myproject.com/helloworld.txt")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("OkHttp", "Call Failed:" + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("OkHttp", "Call succeeded:" + response.message());
            }
        });

以上是一个同步请求和异步请求的例子,都是先通过OKHttpClient的newCall方法返回一个请求对象RealCall,如下

  @Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }

在RealCall中同步请求执行execute,异步请求则执行enqueue,单从方法名字上来理解的话,execute是直接执行任务的意思,enqueue则好像是先放入到某个队列中

  //同步请求execute方法
  @Override public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    try {
      //调用Dispatcher类的execute方法,把请求添加到正在执行同步任务队列中
      client.dispatcher().executed(this);
      //然后通过OKhttp的拦截器链策略去完成请求,返回请求结果
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } catch (IOException e) {
      eventListener.callFailed(this, e);
      throw e;
    } finally {
      client.dispatcher().finished(this);
    }
  }

  //通过拦截器链策略执行请求
  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));
    //拦截器链的执行节点,这是第一个节点,参数this就是当前的请求RealCall实例,把请求传递
    //连接器链去执行
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }


  //异步请求enqueue方法
  @Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    //调用Dispatcher类的enqueue方法
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }

后面任务又交给了Dispatcher去处理,Dispatcher类在OKhttp中充当了任务调度器的作用,它管理着OKhttp的线程池服务和几个队列Deque,任务的执行均由Dispatcher来调度管理

public final class Dispatcher {
  //同一时间的最大请求数,就是异步请求线程的最大数量
  private int maxRequests = 64;
  //对同一个主机同一时间内的最大请求数
  private int maxRequestsPerHost = 5;
  private @Nullable Runnable idleCallback;
  //线程池服务
  private @Nullable ExecutorService executorService;
  //几个重要的任务队列
  private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
  private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

  public Dispatcher(ExecutorService executorService) {
    this.executorService = executorService;
  }

  public Dispatcher() {
  }

  //创建线程池服务
  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;
  }
 ...
}

Dispatcher类的几个重要属性说明:

1.readyAsyncCalls:待执行的异步任务队列

2.runningAsyncCalls:执行中的异步任务队列

3.runningSyncCalls:执行中的同步任务队列

4.executorService:线程池服务

Dispatcher中维护着一个线程池,此线程池的特点是,核心线程数为0,最大线程数为Integer.MAX_VALUE,非核心线程的最大空闲时间为60秒, 任务队列用SynchronousQueue队列,这是一个无缓冲的阻塞队列,也就是说有任务到达的时候,只要没有空闲线程,就会创建一个新的线程来执行

其实这个线程池和JDK提供的newCachedThreadPool创建的线程池是一样的,这种线程池一般适合于并发量大的轻任务,因为不缓存任务,所以它能够快速地执行任务,基本上不阻塞等待

一. 同步请求任务

在同步请求任务中,调用的是Dispatcher的execute方法

  synchronized void executed(RealCall call) {
    runningSyncCalls.add(call);
  }

实际上这里只是把任务添加到执行中的同步任务队列中,这是一个用数组实现的双端队列,添加请求任务之后,在RealCall中直接通过getResponseWithInterceptorChain方法获取了请求结果,其实里面是通过OKhttp的拦截器链策略去完成请求的,关于OKhttp的拦截器链后面再说,任务结束后,就调用Dispatcher的finished方法

  void finished(RealCall call) {
    finished(runningSyncCalls, call, false);
  }


  private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
    int runningCallsCount;
    Runnable idleCallback;
    synchronized (this) {
      //将任务从队列中移除  
      if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
      if (promoteCalls) promoteCalls();
      runningCallsCount = runningCallsCount();
      idleCallback = this.idleCallback;
    }

    if (runningCallsCount == 0 && idleCallback != null) {
      idleCallback.run();
    }
  }

finished方法就是将已经执行完毕的任务从队列中移除,到此整个同步请求任务就结束了

二.异步请求任务

和同步请求不一样,异步请求是先调用RealCall的enqueue方法

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

然后是Dispatcher的enqueue方法,将当前请求任务RealCall和请求回调responseCallback接口封装成一个异步任务AsyncCall,传参给enqueue方法

来看看Dispatcher的enqueue方法

  synchronized void enqueue(AsyncCall call) {
    //默认maxRequests 为60,maxRequestsPerHost为5
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
      runningAsyncCalls.add(call);
      executorService().execute(call);
    } else {
      //添加到等待执行的异步任务队列
      readyAsyncCalls.add(call);
    }
  }

如果正在执行的异步请求任务数量小于maxRequests 并且单一Host的请求数小于maxRequestsPerHost,那么将任务添加到正在执行任务队列,然后将任务交由线程池去执行,否则将任务添加到待执行任务队列中等待执行

从上面得知,异步请求中会通过maxRequests来控制任务的最大并发数和通过maxRequestsPerHoset来控制单一Host的任务最大并发数,然后任务的执行交给线程池处理,任务对象是AsyncCall,所以来看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 {
          eventListener.callFailed(RealCall.this, e);
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        //请求结束回调
        client.dispatcher().finished(this);
      }
    }

和同步请求一样,还是通过OKhttp的拦截器链策略来完成请求任务并返回结果,请求结束调用Dispatcher的finished方法,但异步请求的finisheh处理和同步请求不一样

  void finished(AsyncCall call) {
    //注意异步请求的时候第三个参数为true,而同步请求为false
    finished(runningAsyncCalls, call, true);
  }

  private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
    int runningCallsCount;
    Runnable idleCallback;
    synchronized (this) {
      if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
      //如果异步请求,调用promoteCalls方法,下一步继续执行待执行的异步任务  
      if (promoteCalls) promoteCalls();
      runningCallsCount = runningCallsCount();
      idleCallback = this.idleCallback;
    }

    if (runningCallsCount == 0 && idleCallback != null) {
      idleCallback.run();
    }
  }

关键是promoteCalls方法,一个异步任务执行完毕以后,此方法将触发下一个待执行任务的执行

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

 

三.总结

从上面的分析可以看到,OKhttp的任务主要在Dispatcher中进行调度分发,然后不管是同步请求还是异步请求,它们都是通过OKhttp的拦截器策略去完成的,所以读完本篇文章,肯定留下一个疑问,OKhttp的拦截器链又是怎么实现的?

下一篇分析OKhttp拦截器链的实现原理

OKHttp 3.10源码解析(二):拦截器链

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值