一、摘要

okhttp3在android应用开发中是现今最牛(哔)的网络交易框架,不接受反驳。

今儿个咱们就来看看到底okhttp3内部是如何实现的,这篇文章咱从okhttp3整体框架方面出发,解析okhttp3的源码。

okhttp缓存原理(okhttp3源码分析-架构全面解析)(1)

二、okhttp3源码地址

okhttp3框架源码地址: https://github.com/square/okhttp

三、okhttp3简单使用
  1. OkHttpClient client = new OkHttpClient.Builder().build();
  2. request request = new Request.Builder().
  3. url("https://github.com/cozing").
  4. build();
  5. Call call = client.newCall(request);
  6. try {
  7. //1.同步请求方式
  8. Response response = call.execute();
  9. //2.异步请求方式
  10. call.enqueue(new Callback() {
  11. @Override
  12. public void onFailure(Call call, IOException e) {
  13. Log.w("cozing", "交易失败");
  14. }
  15. @Override
  16. public void onResponse(Call call, Response response) throws IOException {
  17. Log.w("cozing", "交易成功");
  18. }
  19. });
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }

这是使用okhttp3发送一个简单交易的流程,其中包括同步请求和异步请求:

1.同步请求调用的方法是call.execute(),内部采用的是线程阻塞方式直接将结果返回到Response,后面咱们会详细讲解;

2.异步请求调用的方法是call.enqueue(Callback callback),该方法需要传入一个Callback等待结果回调的接口,交易结果在onFailure()(失败)和onResponse()(成功)中返回。

那么,接下来咱们来看看okhttp3的源码的整体流程。

四、整体架构流程图

okhttp缓存原理(okhttp3源码分析-架构全面解析)(2)

接下来咱们将根据这个整体架构图来来看看okhttp3的内部实现。

五、流程详解

1.创建OkHttpClient

首先创建OkHttpClient对象,OkHttpClient是okhttp3框架的客户端,用于发送http请求(Requests)和读取读取交易返回数据(Responses)。官方建议使用单例创建OkHttpClient,即一个进程中只创建一次即可,以后的每次交易都使用该实例发送交易。这是因为OkHttpClient拥有自己的连接池和线程池,这些连接池和线程池可以重复使用,这样做利于减少延迟和节省内存,如果咱们每次发交易都创建一个OkHttpClient的话,将会浪费很多内存资源。

除了上面例子的创建方式:

  1. OkHttpClient client = new OkHttpClient.Builder().build();
  2. Request request = new Request.Builder().
  3. url("https://github.com/cozing").
  4. build();
  5. Call call = client.newCall(request);
  6. ...

还有一种方式创建OkHttpCleint对象的方式:

  1. OkHttpClient client = new OkHttpClient();
  2. Request request = new Request.Builder().
  3. url("https://github.com/cozing").
  4. build();
  5. Call call = client.newCall(request);
  6. ...

这两种创建方式内部实现,第一种采用构建者模式创建OkHttpClient对象,这种方式可以自定义Builder内部的每一个参数属性,第二种采用普通的创建实例方式创建一个OkHttpClient对象,内部创建了一个默认的Builder,因此这种方式使用默认Builder的内部属性。

2.创建Call对象

一个Call对象表示一次请求,每一次交易请求都会生产一个新的Call,Call其实是一个接口对象,它的具体实现类是RealCall,Call的创建过程:

  1. ...
  2. Request request = new Request.Builder().
  3. url("https://github.com/cozing").
  4. build();
  5. Call call = client.newCall(request);
  6. ...

可以看到在创建Call对象时候传进去了一个Request对象,Request对象表示用户的交易请求参数,咱们看看它的内部实现:

  1. public final class Request {
  2. final HttpUrl url;
  3. final String method;
  4. final Headers headers;
  5. final @Nullable RequestBody body;
  6. final Object tag;
  7. ...
  8. Request(Builder builder) {
  9. this.url = builder.url;
  10. this.method = builder.method;
  11. this.headers = builder.headers.build();
  12. this.body = builder.body;
  13. this.tag = builder.tag != null ? builder.tag : this;
  14. }
  15. ...
  16. }

可以看到,里面包括:

url:交易请求地址;

method:请求方式,比如:get/post/http...等请求方式;

headers:请求头;

body:请求体;

咱们这时看看Call的创建方法client.newCall(request)的内部实现:

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

继续看RealCall.newRealCall():

  1. static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
  2. // Safely publish the Call instance to the EventListener.
  3. RealCall call = new RealCall(client, originalRequest, forWebSocket);
  4. call.eventListener = client.eventListenerFactory().create(call);
  5. return call;
  6. }

可以看到确实如上面咱们所说,最后创建的是RealCall对象。

3.请求交易

okhttp3中提供了两种交易方式:一种是同步请求,第二种是异步请求。同步请求调用call.execute()方法,异步请求调用call.enqueue(Callback callback)方法,

在看两个请求方式的实现之前,咱们先来看okhttp3中一个重要成员Dispatcher(调度器):

(1)Dispatcher(调度器):

Dispatcher是okhttp3的任务调度核心类,负责管理同步和异步的请求,管理每一个请求任务的请求状态,并且其内部维护了一个线程池用于执行相应的请求,Dispatcher的实现框架图:

okhttp缓存原理(okhttp3源码分析-架构全面解析)(3)

Dispatcher内部维护了两个队列:

  1. public final class Dispatcher {
  2. ...
  3. //用于保存等待执行的异步队列
  4. private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
  5. //用于保存正在执行的异步队列
  6. private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
  7. ...
  8. }

两个队列的作用可以看上面注释,那么为何要使用这两个队列呢?咱们可以这么理解:把Dispatcher当成生产者,把线程池当成消费者,当生产者生产的线程大于消费者所能承受的最大范围,就把未能及时执行的任务保存在readyAsyncCalls队列中,当时机成熟,也就是线程池有空余线程可以执行时,会调用promoteCall()这个方法把等待队列中的任务取出放到线程池中执行,并且把这个任务转移到runningAsyncCalls队列中去。

接下来咱们分别看看同步请求和异步请求的实现过程,并详细说一下他们是如何实现的。

(2).同步交易请求

call.execute()实现方式:

  1. final class RealCall implements Call {
  2. ...
  3. @Override public Response execute() throws IOException {
  4. synchronized (this) {
  5. if (executed) throw new IllegalStateException("Already Executed");
  6. executed = true;
  7. }
  8. captureCallStackTrace();
  9. eventListener.callStart(this);
  10. try {
  11. //①调用调度器dispatcher的executed方法
  12. client.dispatcher().executed(this);
  13. Response result = getResponseWithInterceptorChain();
  14. if (result == null) throw new IOException("Canceled");
  15. return result;
  16. } catch (IOException e) {
  17. eventListener.callFailed(this, e);
  18. throw e;
  19. } finally {
  20. //②调用分配器Dispatcher的finish()方法
  21. client.dispatcher().finished(this);
  22. }
  23. }
  24. ...
  25. }

咱们看看注释①部分的实现,调用了 client.dispatcher()的executed()方法,来看client.dispatcher()的内部实现:

  1. public class OkHttpClient{
  2. ...
  3. final Dispatcher dispatcher;
  4. ...
  5. public Dispatcher dispatcher() {
  6. return dispatcher;
  7. }
  8. ...
  9. }

可以看到实际调用的是Dispatcher调度器的executed()方法,继续看Dispatcher的实现:

  1. public final class Dispatcher {
  2. ...
  3. private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
  4. ...
  5. synchronized void executed(RealCall call) {
  6. runningSyncCalls.add(call);
  7. }
  8. ...
  9. }

到此咱们可以知道这部分是将这次交易的请求RealCall存进了Deque队列,Deque是一个双向队列接口,Deque接口具有丰富的抽象数据形式,它支持从队列两端点检索和插入元素,在此咱们不对其做过多讲解。

接下来看到注释②中,不管结果交易结果如何,都会调用finally中的client.dispatcher().finished(this)将本次请求从队列中移除。

接下来调用该方法:

  1. ...
  2. Response result = getResponseWithInterceptorChain();
  3. ...

这个方法是okhttp3的实现精髓点之一,这部分咱先放一边,将会在异步请求中一起讲解。

(3).异步交易请求

call.enqueue(Callback callback)实现方式:

  1. final class RealCall implements Call {
  2. ...
  3. @Override public void enqueue(Callback responseCallback) {
  4. synchronized (this) {
  5. if (executed) throw new IllegalStateException("Already Executed");
  6. executed = true;
  7. }
  8. captureCallStackTrace();
  9. eventListener.callStart(this);
  10. //①调用调度器dispatcher的enqueue()
  11. client.dispatcher().enqueue(new AsyncCall(responseCallback));
  12. }
  13. ...
  14. }

当调用此次异步请求交易方法的时候,内部是调用了调度器dispatcher的equeue(new AsyncCall(responseCallback))方法,该方法需要传入一个AsyncCall的对象。

接下来看dispatcher的equeue(new AsyncCall(responseCallback))方法的实现:

  1. public final class Dispatcher {
  2. ...
  3. private int maxRequests = 64;
  4. private int maxRequestsPerHost = 5;
  5. ...
  6. private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
  7. ...
  8. synchronized void enqueue(AsyncCall call) {
  9. if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
  10. runningAsyncCalls.add(call);
  11. executorService().execute(call);
  12. } else {
  13. readyAsyncCalls.add(call);
  14. }
  15. }
  16. ...
  17. }

先判断当前运行中的请求数是否小于设定的最大请求数量,默认最大请求数是同时执行64个请求,并且判断当前运行中的共同主机的请求数量是否小于设定的最大请求数量,默认同一主机的请求数量最大值为5,当两者条件都成立的时候会调用executorService()的execute(call)方法;两者中只要有一个条件不成立,就会调用redyAsncCalls.add(call)将表示此次请求的call对象存在readyAsyncCalls队列中,readyAsyncCalls表示已准备好并等待执行请求的队列,当有空闲网络请求线程时,会从该队列中取出并执行网络请求。

接下来看executorService().execute(call):

  1. public final class Dispatcher {
  2. ...
  3. public synchronized ExecutorService executorService() {
  4. if (executorService == null) {
  5. executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
  6. new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
  7. }
  8. return executorService;
  9. }
  10. ...
  11. }

可以看到调度器Dispatcher内部维护了一个ThreadPoolExecutor线程池,并直接将call对象传入线程池执行。

咱们在刚才知道这个call的实现对象是AsyncCall,来看看内部实现:

  1. final class RealCall implements Call {
  2. ...
  3. final class AsyncCall extends NamedRunnable {
  4. private final Callback responseCallback;
  5. AsyncCall(Callback responseCallback) {
  6. super("OkHttp %s", redactedUrl());
  7. this.responseCallback = responseCallback;
  8. }
  9. String host() {
  10. return originalRequest.url().host();
  11. }
  12. Request request() {
  13. return originalRequest;
  14. }
  15. RealCall get() {
  16. return RealCall.this;
  17. }
  18. @Override protected void execute() {
  19. boolean signalledCallback = false;
  20. try {
  21. Response response = getResponseWithInterceptorChain();
  22. if (retryAndFollowUpInterceptor.isCanceled()) {
  23. signalledCallback = true;
  24. responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
  25. } else {
  26. signalledCallback = true;
  27. responseCallback.onResponse(RealCall.this, response);
  28. }
  29. } catch (IOException e) {
  30. if (signalledCallback) {
  31. // Do not signal the callback twice!
  32. Platform.get().log(INFO, "Callback failure for " toLoggableString(), e);
  33. } else {
  34. eventListener.callFailed(RealCall.this, e);
  35. responseCallback.onFailure(RealCall.this, e);
  36. }
  37. } finally {
  38. client.dispatcher().finished(this);
  39. }
  40. }
  41. }
  42. ...
  43. }

可以看到AsyncCall是RealCall的一个内部类,继承自NamedRunnable,再看NamedRunnable:

  1. public abstract class NamedRunnable implements Runnable {
  2. protected final String name;
  3. public NamedRunnable(String format, Object... args) {
  4. this.name = Util.format(format, args);
  5. }
  6. @Override public final void run() {
  7. String oldName = Thread.currentThread().getName();
  8. Thread.currentThread().setName(name);
  9. try {
  10. execute();
  11. } finally {
  12. Thread.currentThread().setName(oldName);
  13. }
  14. }
  15. protected abstract void execute();
  16. }

所以,AsyncCall就是一个Runnable的实现,用来开启一个线程,当网络请求线程池执行该线程的run()方法时,会调用AsyncCall的execute()的方法,最后在execute()方法内部调用了和上面咱们分析的同步请求方法一样的getResponseWithInterceptorChain()。

(4)getResponseWithInterceptorChain()/拦截器链

通过上面的分析咱们知道不管是同步请求还是异步请求,最后都会走getResponseWithInterceptorChain()方法,getResponseWithInterceptorChain()是okhttp3中的精髓设计之一,那么现在咱们来看看这个方法的内部实现:

  1. final class RealCall implements Call {
  2. ...
  3. Response getResponseWithInterceptorChain() throws IOException {
  4. // Build a full stack of interceptors.
  5. List<Interceptor> interceptors = new ArrayList<>();
  6. interceptors.addAll(client.interceptors());
  7. interceptors.add(retryAndFollowUpInterceptor);
  8. interceptors.add(new BridgeInterceptor(client.cookieJar()));
  9. interceptors.add(new CacheInterceptor(client.internalCache()));
  10. interceptors.add(new ConnectInterceptor(client));
  11. if (!forWebSocket) {
  12. interceptors.addAll(client.networkInterceptors());
  13. }
  14. interceptors.add(new CallServerInterceptor(forWebSocket));
  15. Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
  16. originalRequest, this, eventListener, client.connectTimeoutMillis(),
  17. client.readTimeoutMillis(), client.writeTimeoutMillis());
  18. return chain.proceed(originalRequest);
  19. }
  20. }

这个方法是通过拦截器链对请求数据和返回数据进行处理,内部采用责任链模式,将每一个拦截器对应负责的处理任务进行严格分配,最后将交易结果返回并回调到暴露给调用者的接口上。

这些拦截器包括:

①.用户自定义的拦截器

②.retryAndFollowUpInterceptor:重试和重定向拦截器,主要负责网络失败重连。

③.BridgeInterceptor:主要负责添加交易请求头。

④.CacheInterceptor:缓存拦截器,主要负责拦截缓存。

⑤.ConnectInterceptor:网络连接拦截器,主要负责正式开启http请求。

⑥.CallServerInterceptor:负责发送网络请求和读取网络响应。

有关每个拦截器的具体实现和内部流程,咱们将会在下一篇文章中详细讲解,这篇文章咱们主要还是分析okhttp3的整体架构。

根据上面的源码可以看到,最后交给了了RealInterceptorChain(拦截器链类)这个真正的处理类,并调用RealInterceptorChain的proceed()方法来实现,具体实现:

  1. public final class RealInterceptorChain implements Interceptor.Chain {
  2. ...
  3. @Override public Response proceed(Request request) throws IOException {
  4. return proceed(request, streamAllocation, httpCodec, connection);
  5. }
  6. public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
  7. RealConnection connection) throws IOException {
  8. if (index >= interceptors.size()) throw new AssertionError();
  9. calls ;
  10. if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
  11. throw new IllegalStateException("network interceptor " interceptors.get(index - 1)
  12. " must retain the same host and port");
  13. }
  14. // 保证此次调用的唯一性
  15. if (this.httpCodec != null && calls > 1) {
  16. throw new IllegalStateException("network interceptor " interceptors.get(index - 1)
  17. " must call proceed() exactly once");
  18. }
  19. // 调用拦截器链的下一个拦截器
  20. RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
  21. connection, index 1, request, call, eventListener, connectTimeout, readTimeout,
  22. writeTimeout);
  23. Interceptor interceptor = interceptors.get(index);
  24. // 注释①
  25. Response response = interceptor.intercept(next);
  26. if (httpCodec != null && index 1 < interceptors.size() && next.calls != 1) {
  27. throw new IllegalStateException("network interceptor " interceptor
  28. " must call proceed() exactly once");
  29. }
  30. if (response == null) {
  31. throw new NullPointerException("interceptor " interceptor " returned null");
  32. }
  33. if (response.body() == null) {
  34. throw new IllegalStateException(
  35. "interceptor " interceptor " returned a response with no body");
  36. }
  37. return response;
  38. }
  39. }

看注释①处,会调用拦截器的intercept(next)方法,只有当前拦截器的response返回结果时,才会执行下一个拦截器,因此得出结论:下一个拦截器依赖于当前拦截器的返回,可以保证拦截器的依次执行。

在拦截器链中执行的结果,在同步请求中会直接在response返回,异步请求:

  1. final class RealCall implements Call {
  2. ...
  3. final class AsyncCall extends NamedRunnable {
  4. ...
  5. @Override public Response execute() throws IOException {
  6. ...
  7. responseCallback.onResponse(RealCall.this, response);
  8. ...
  9. }
  10. ...
  11. }

异步请求时会把拦截器链的处理结果通过Callback的onReponse回调给用户。

五、总结

至此,okhttp3的整体架构分析完毕,建议咱们课后可以跟着源码一步步去理解,去了解okhttp3的作者大神们的思想,然后应用到咱们的项目开发中。当然,okhttp3是一个很庞大的一个框架,咱们这篇文章主要是从它的整体架构方面对其做了简单的分析,内部的实现逻辑和思想都很值得咱们认真思考和细细品味。

okhttp缓存原理(okhttp3源码分析-架构全面解析)(4)

,