OkHttpClient源码分析(三)—— 缓存机制介绍

643 阅读5分钟

在讲解CacheInterceptor之前,我们先了解一下OkHttp的缓存机制,主要是Cache这个类,演示下如何使用OkHttp的缓存:

private void cacheOkHttpRequest(){
        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .cache(new Cache(new File(Environment.getExternalStorageDirectory()+ "/okttp_caches"),24*1024*1024))
                .build();
        Request request = new Request
                .Builder()
                .url("http://www.ifeng.com")
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            Log.e(TAG,"response: " + response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

上述代码中在OkHttpClient的Builder中配置了cache,传入缓存目录的File对象以及缓存最大容量(单位字节),这里请求了凤凰网,请求成功后,OkHttp会将请求的相关数据进行缓存,当下次请求无法链接到网络的时候,它会读取缓存并将数据返回。

根据缓存的流程,我们可以猜测到Cache类会有保存和读取缓存的方法,我们通过查看Cache类的源码,果然发现了put()和get()方法,分别用于保存缓存和读取缓存:

@Nullable CacheRequest put(Response response) {
    //获取请求方法
    String requestMethod = response.request().method();
    
    //一、传入请求方法,判断是否要缓存
    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")) {
      // Don't cache non-GET responses. We're technically allowed to cache
      // HEAD requests and some POST requests, but the complexity of doing
      // so is high and the benefit is low.
      return null;
    }

    if (HttpHeaders.hasVaryAll(response)) {
      return null;
    }

    //三、创建缓存实体
    Entry entry = new Entry(response);
   
    //四、使用 DiskLruCache缓存策略
    DiskLruCache.Editor editor = null;
    try {
      editor = cache.edit(key(response.request().url()));
      if (editor == null) {
        return null;
      }
      entry.writeTo(editor);
      return new CacheRequestImpl(editor);
    } catch (IOException e) {
      abortQuietly(editor);
      return null;
    }
  }

在分析这个方法之前,需要先知道的是,OkHttp默认只会对get请求进行缓存,post请求是不会进行缓存,这也是有道理的,因为get请求的数据一般是比较持久的,而post一般是交互操作,没太大意义进行缓存;当然,也可以自己实现post请求的缓存操作,这个需要根据自己的项目需求来。

回到put()方法的分析,上述代码中,先是对请求方法进行了判断,是否需要缓存下来。

注释一处,调用了HttpMethod的invalidatesCache():

public final class HttpMethod {
  public static boolean invalidatesCache(String method) {
    return method.equals("POST")
        || method.equals("PATCH")
        || method.equals("PUT")
        || method.equals("DELETE")
        || method.equals("MOVE");     // WebDAV
  }
  ...
}

如果请求方法是POST、PATCH、PUT、DELETE以及MOVE中一个,就会将当前请求的缓存移除。

接着判断是否是非GET请求,如果是则不进行缓存。

最后,开始进行缓存的操作,注释三处创建了一个Entry类,传入Response对象,查看其构造方法:

  Entry(Response response) {
      this.url = response.request().url().toString();
      this.varyHeaders = HttpHeaders.varyHeaders(response);
      this.requestMethod = response.request().method();
      this.protocol = response.protocol();
      this.code = response.code();
      this.message = response.message();
      this.responseHeaders = response.headers();
      this.handshake = response.handshake();
      this.sentRequestMillis = response.sentRequestAtMillis();
      this.receivedResponseMillis = response.receivedResponseAtMillis();
 }

Entry会将请求url、头部、请求方式、协议、响应码等一系列参数保存下来。

注释四处,创建缓存策略,OkHttp的缓存策略使用的是DiskLruCache,DiskLruCache是用于磁盘缓存的一套解决框架,OkHttp对DiskLruCache稍微做了点修改,并且OkHttp内部维护着清理内存的线程池,通过这个线程池完成缓存的自动清理和管理工作,本篇不做过多介绍。

获取到DiskLruCache的Editor对象后,通过它的edit方法创建缓存文件,传入缓存的文件名,文件名的生成是通过key()方法将请求url进行MD5加密并获取它的十六进制表示形式。

接着执行Entry对象的writeTo()方法并传入Editor对象,writeTo()方法是将缓存信息存储在本地:

public void writeTo(DiskLruCache.Editor editor) throws IOException {
      BufferedSink sink = Okio.buffer(editor.newSink(ENTRY_METADATA));

      //缓存请求的url
      sink.writeUtf8(url)
          .writeByte('\n');
      //缓存请求方法
      sink.writeUtf8(requestMethod)
          .writeByte('\n');
      //缓存请求头部大小
      sink.writeDecimalLong(varyHeaders.size())
          .writeByte('\n');
     
     //缓存请求头部信息
     //缓存协议,响应码
     //缓存响应头部信息
     //缓存发送请求时间以及响应时间
      ...
      
      //判断是否是https请求
      if (isHttps()) {
        //缓存相关信息
        sink.writeByte('\n');
        sink.writeUtf8(handshake.cipherSuite().javaName())
            .writeByte('\n');
        writeCertList(sink, handshake.peerCertificates());
        writeCertList(sink, handshake.localCertificates());
        sink.writeUtf8(handshake.tlsVersion().javaName()).writeByte('\n');
      }
      sink.close();
    }

上述代码中并没有对响应主体的body进行缓存,在调用Entry的writeTo()方法之后,返回了一个CacheRequestImpl对象:

  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();
        }
      };
    }

这里我们可以看到Repsonse的body是在这里被写入缓存的,CacheRequestImpl实现CacheRequest接口,用于暴露给缓存拦截器,缓存拦截器可以通过这个类来写入或更新缓存的数据。

接下来分析获取缓存的get()方法:

@Nullable Response get(Request request) {
    String key = key(request.url());
    DiskLruCache.Snapshot snapshot;
    Entry entry;
    try {
      snapshot = cache.get(key);
      if (snapshot == null) {
        return null;
      }
    } catch (IOException e) {
      // Give up because the cache cannot be read.
      return null;
    }

    try {
      entry = new Entry(snapshot.getSource(ENTRY_METADATA));
    } 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;
  }

显示通过请求的url获取到缓存对应的文件名key,然后创建一个DiskLruCache.Snapshot缓存快照对象,根据key获取对应的缓存快照,如果获取到的为null,则说明没有找到缓存,直接返回null;如果找到对应的缓存快照,则根据快照生成Entry对象,再通过调用Entry的response()方法获取到缓存的Response对象。

response()方法:

public Response response(DiskLruCache.Snapshot snapshot) {
      String contentType = responseHeaders.get("Content-Type");
      String contentLength = responseHeaders.get("Content-Length");
      Request cacheRequest = new Request.Builder()
          .url(url)
          .method(requestMethod, null)
          .headers(varyHeaders)
          .build();
      return new Response.Builder()
          .request(cacheRequest)
          .protocol(protocol)
          .code(code)
          .message(message)
          .headers(responseHeaders)
          .body(new CacheResponseBody(snapshot, contentType, contentLength))
          .handshake(handshake)
          .sentRequestAtMillis(sentRequestMillis)
          .receivedResponseAtMillis(receivedResponseMillis)
          .build();
    }
}

这里实际上根据缓存的数据创建了Request请求,并返回生成的Response对象。

获取到缓存的Response对象后,get()方法里将其与传入的request进行比对,如果二者不是成对的,则关闭流且返回null,如果是的话,则返回由缓存数据生成的Response对象。

关于OkHttpClient的缓存机制,这里已经初步介绍完了,本篇主要是为介绍CacheInterceptor做铺垫,下一篇我们将了解第三个拦截器CacheInterceptor缓存拦截器,感兴趣的朋友可以继续阅读:

OkHttpClient源码分析(四)—— CacheInterceptor