OkHttp源码--缓存

HTTP的缓存规则

可分为两大类:

  • 强制缓存
  • 对比缓存
    不同点就是:强制缓存如果生效(有缓存数据且未失效),不需要再和服务器发生交互,,而对比缓存不管是否生效,都需要与服务端发生交互。两类缓存规则可以同时存在,强制缓存优先级高于对比缓存,也就是说,当执行强制缓存的规则时,如果缓存生效,直接使用缓存,不再执行对比缓存规则。

强制缓存

在没有缓存数据的时候,浏览器向服务器请求数据时,服务器会将数据和缓存规则一并返回,缓存规则信息包含在响应header中。响应header中会有两个字段来标明失效规则(Expires/Cache-Control)。

Expires

到期时间,它是http 1.0的东西,到期时间是由服务端生成的,但是客户端时间可能跟服务端时间有误差,这就会导致缓存命中的误差,所以http 1.1使用Cache-Control替代。(现在默认浏览器使用http 1.1)

Cache-Control

OkHttp根据HTTP头部中的CacheControl进行缓存控制。
Cache-Control首部的一些值既可以用于请求首部又可以用于响应首部。
private: 客户端可以缓存 (默认为private)
public: 客户端和代理服务器都可缓存(前端的同学,可以认为public和private是一样的)

对比缓存

浏览器第一次请求数据时,服务器会将缓存标识与数据一起返回给客户端,客户端将二者备份至缓存数据库中。
再次请求数据时,客户端将从缓存数据库得到的备份的缓存标识发送给服务器,服务器根据缓存标识进行判断,判断成功后,返回304状态码,通知客户端比较成功,可以使用缓存数据。
对比缓存生效时,服务端在进行标识比较后,只返回header部分,通过状态码通知客户端使用缓存,不再需要将报文主体部分返回给客户端。

缓存标识

缓存标识在请求header和响应header间传递,一般分为两种标识传递;Last-Modified / If-Modified-Since和Etag / If-None-Match(优先级高)

Last-Modified

服务器在响应请求时,告诉浏览器资源的最后修改时间。

If-Modified-Since

再次请求服务器时,通过此字段通知服务器上次请求时,服务器返回的资源最后修改时间。
服务器收到请求后发现有头If-Modified-Since 则与被请求资源的最后修改时间进行比对。
若资源的最后修改时间大于If-Modified-Since,说明资源又被改动过,则响应整片资源内容,返回状态码200;
若资源的最后修改时间小于或等于If-Modified-Since,说明资源无新修改,则响应HTTP 304,告知浏览器继续使用所保存的cache。

Etag

服务器响应请求时,告诉浏览器当前资源在服务器的唯一标识(生成规则由服务器决定)。

If-None-Match

再次请求服务器时,通过此字段通知服务器客户端缓存数据的唯一标识。
服务器收到请求后发现有头If-None-Match 则与被请求资源的唯一标识进行比对,
不同,说明资源又被改动过,则响应整片资源内容,返回状态码200;
相同,说明资源无新修改,则响应HTTP 304,告知浏览器继续使用所保存的cache。

Cache类

将响应缓存到文件系统中。
Cache中很多方法都是通过DiskLruCache实现的,OkHttp在DiskLruCache的基础上进行修改,将IO操作改成了Okio。
为了测量缓存效率,Cache类跟踪三个数据:

  • 请求数量
  • 网络命中数:需要请求进行网络请求的请求数量
  • 缓存命中数:响应由缓存提供的请求的数量

Cache类的内部有一个InternalCache(本身是一个接口)的实现类。

// 接口使用匿名内部类
final InternalCache internalCache = new InternalCache() {
    // 得到缓存
    @Override public @Nullable Response get(Request request) throws IOException {
      return Cache.this.get(request);
    }

    // 缓存响应
    @Override public @Nullable CacheRequest put(Response response) throws IOException {
      return Cache.this.put(response);
    }

    // 移除缓存
    @Override public void remove(Request request) throws IOException {
      Cache.this.remove(request);
    }

    // 更新缓存
    @Override public void update(Response cached, Response network) {
      Cache.this.update(cached, network);
    }

    @Override public void trackConditionalCacheHit() {
      Cache.this.trackConditionalCacheHit();
    }

    @Override public void trackResponse(CacheStrategy cacheStrategy) {
      Cache.this.trackResponse(cacheStrategy);
    }
};

InternalCache接口中每个方法的实现都交给外部类Cache来完成,看Cache类的各个方法(主要交给DiskLruCache)。

Cache # put()

缓存响应

@Nullable CacheRequest put(Response response) {
    String requestMethod = response.request().method();
    // 对request的方法进行校验
    if (HttpMethod.invalidatesCache(response.request().method())) {
      try {
        // 若method为POST PATCH PUT DELETE MOVE其中一个,删除现有缓存并结束
        remove(response.request());
      } catch (IOException ignored) {
        // The cache cannot be written.
      }
      return null;
    }
    
    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.
      // 虽然技术上允许缓存POST请求及HEAD请求,但这样实现较为复杂且收益不高
      // 因此OkHttp只允许缓存GET请求
      return null;
    }

    // 如果响应头中含有星号,也不进行缓存
    if (HttpHeaders.hasVaryAll(response)) {
      return null;
    }


    // 使用DiskLruCache进行缓存
    // 使用响应创建一个Entry(Cache中的),将响应中的内容保存起来
    Entry entry = new Entry(response);
    // 这个类也是不能new的,需要调用edit()来获取实例
    DiskLruCache.Editor editor = null;
    try {
      // cache是DiskLruCache的实例
      editor = cache.edit(key(response.request().url()));
      if (editor == null) {
        return null;
      }
      // 写入请求头部分信息和响应头
      entry.writeTo(editor);
      // 返回CacheRequestImpl对象(写入响应主体)
      return new CacheRequestImpl(editor);
    } catch (IOException e) {
      abortQuietly(editor);
      return null;
    }
}

Cache # key()

public static String key(HttpUrl url) {
    // 对其请求的url做MD5,然后获得其值
    return ByteString.encodeUtf8(url.toString()).md5().hex();
}

DiskLruCache # edit()

来获取Editor实例

/**
   * Returns an editor for the entry named {@code key}, or null if another edit is in progress.
   */
public @Nullable Editor edit(String key) throws IOException {
    return edit(key, ANY_SEQUENCE_NUMBER);
  }

  synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
    // 初始化
    initialize(); 

    checkNotClosed();
    validateKey(key);
    // 通过key获得Entry
    Entry entry = lruEntries.get(key);
    if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null
        || entry.sequenceNumber != expectedSequenceNumber)) {
      return null; // Snapshot is stale. 过期的
    }
    
    // 当前disklrucache entry正在被其他对象操作
    if (entry != null && entry.currentEditor != null) {
      return null; // Another edit is in progress.
    }
    
    if (mostRecentTrimFailed || mostRecentRebuildFailed) {
      // The OS has become our enemy! If the trim job failed, it means we are storing more data than
      // requested by the user. Do not allow edits so we do not go over that limit any further. If
      // the journal rebuild failed, the journal writer will not be active, meaning we will not be
      // able to record the edit, causing file leaks. In both cases, we want to retry the clean up
      // so we can get out of this state!
      executor.execute(cleanupRunnable);
      return null;
    }

    // 日志接入DIRTY记录
    // Flush the journal before creating files to prevent file leaks.
    journalWriter.writeUtf8(DIRTY).writeByte(' ').writeUtf8(key).writeByte('\n');
    journalWriter.flush();

    if (hasJournalErrors) {
      return null; // Don't edit; the journal can't be written.
    }

    if (entry == null) {
      // DiskLruCache中的Entry
      entry = new Entry(key);
      lruEntries.put(key, entry);
    }
    Editor editor = new Editor(entry);
    entry.currentEditor = editor;
    return editor;
}

Entry # writeTo()

只是写入请求头部分信息和响应头,响应主体主要在CacheRequestImpl中保存。缓存中的key值是请求的URL的MD5值,而value包括请求和响应部分。

public void writeTo(DiskLruCache.Editor editor) throws IOException {
      BufferedSink sink = Okio.buffer(editor.newSink(ENTRY_METADATA));
    
      // 在editor的输出流中写入请求的相关信息
      sink.writeUtf8(url)
          .writeByte('\n');
      sink.writeUtf8(requestMethod)
          .writeByte('\n');
      sink.writeDecimalLong(varyHeaders.size())
          .writeByte('\n');
      for (int i = 0, size = varyHeaders.size(); i < size; i++) {
        sink.writeUtf8(varyHeaders.name(i))
            .writeUtf8(": ")
            .writeUtf8(varyHeaders.value(i))
            .writeByte('\n');
      }

      // 写入响应行
      sink.writeUtf8(new StatusLine(protocol, code, message).toString())
          .writeByte('\n');
      // 写入响应头
      sink.writeDecimalLong(responseHeaders.size() + 2)
          .writeByte('\n');
      for (int i = 0, size = responseHeaders.size(); i < size; i++) {
        sink.writeUtf8(responseHeaders.name(i))
            .writeUtf8(": ")
            .writeUtf8(responseHeaders.value(i))
            .writeByte('\n');
      }
      sink.writeUtf8(SENT_MILLIS)
          .writeUtf8(": ")
          .writeDecimalLong(sentRequestMillis)
          .writeByte('\n');
      sink.writeUtf8(RECEIVED_MILLIS)
          .writeUtf8(": ")
          .writeDecimalLong(receivedResponseMillis)
          .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();
}

CacheRequestImpl

CacheRequestImpl实现了CacheRequest接口,通过这个CacheRequest接口暴露给CacheInterceptor 缓存拦截器的,然后缓存拦截器就可以直接通过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++;
          }
          // ForwardingSink.close()
          super.close();
          // editor.commit还会将dirtyFile重置为cleanFile作为稳定可用的缓存
          editor.commit();
        }
      };
    }

    @Override public void abort() {
      synchronized (Cache.this) {
        if (done) {
          return;
        }
        done = true;
        writeAbortCount++;
      }
      Util.closeQuietly(cacheOut);
      try {
        // 调用abort()方法的话则表示放弃此次写入。
        editor.abort();
      } catch (IOException ignored) {
      }
    }

    @Override public Sink body() {
      return body;
    }
}

Editor # commit()

更新日志,将dirtyFile重置为cleanFile作为稳定可用的缓存

public void commit() throws IOException {
      synchronized (DiskLruCache.this) {
        if (done) {
          throw new IllegalStateException();
        }
        if (entry.currentEditor == this) {
          // abort()第二个参数为false
          completeEdit(this, true);
        }
        done = true;
      }
}

DiskLruCache # completeEdit()

journalFile日志文件对cache每一次读写都对应一条日志记录。DiskLruCache中的每个Entry(key,cleanFiles/dirtyFiles,currentEditor)对应多个文件,其对应的文件数由DiskLruCache.valueCount指定。当前在OkHttp中valueCount为2。即每个cache对应2个cleanFiles,2个dirtyFiles。第一个cleanFiles/dirtyFiles记录cache的meta数据(如URL,创建时间,SSL握手记录等等),第二个文件记录cache的真正内容。cleanFiles记录处于稳定状态的cache结果,dirtyFiles记录处于创建或更新状态的cache
外部访问到的cache快照均为CLEAN状态,更新和创建都只操作DIRTY状态副本,实现了Cache的读写分离。

synchronized void completeEdit(Editor editor, boolean success) throws IOException {
    Entry entry = editor.entry;
    if (entry.currentEditor != editor) {
      throw new IllegalStateException();
    }

    // If this edit is creating the entry for the first time, every index must have a value.
    // 如果这是第一次编辑条目,那么每个索引都必须有一个值
    if (success && !entry.readable) {
      for (int i = 0; i < valueCount; i++) {
        if (!editor.written[i]) {
          editor.abort();
          throw new IllegalStateException("Newly created entry didn't create value for index " + i);
        }
        if (!fileSystem.exists(entry.dirtyFiles[i])) {
          editor.abort();
          return;
        }
      }
    }
    
    // 将dirtyFile重置为cleanFile作为稳定可用的缓存
    for (int i = 0; i < valueCount; i++) {
      File dirty = entry.dirtyFiles[i];
      if (success) {
        if (fileSystem.exists(dirty)) {
          File clean = entry.cleanFiles[i];
          fileSystem.rename(dirty, clean);
          long oldLength = entry.lengths[i];
          long newLength = fileSystem.size(clean);
          entry.lengths[i] = newLength;
          size = size - oldLength + newLength;
        }
      } else {
        // 如果是abort()则删除dirtyfile
        fileSystem.delete(dirty);
      }
    }

    redundantOpCount++;
    entry.currentEditor = null;
    
    // 更新日志,防止日志过分膨胀定时执行日志精简
    if (entry.readable | success) {
      entry.readable = true;
      journalWriter.writeUtf8(CLEAN).writeByte(' ');
      journalWriter.writeUtf8(entry.key);
      entry.writeLengths(journalWriter);
      journalWriter.writeByte('\n');
      if (success) {
        entry.sequenceNumber = nextSequenceNumber++;
      }
    } else {
      lruEntries.remove(entry.key);
      journalWriter.writeUtf8(REMOVE).writeByte(' ');
      journalWriter.writeUtf8(entry.key);
      journalWriter.writeByte('\n');
    }
    journalWriter.flush();

    if (size > maxSize || journalRebuildRequired()) {
      executor.execute(cleanupRunnable);
    }
}

Cache # get()

获取缓存

@Nullable Response get(Request request) {
    // 获得key值
    String key = key(request.url());
    // 从DiskLruCache.Snapshot中得到缓存文件的输入流
    DiskLruCache.Snapshot snapshot;
    Entry entry;
    try {
      // cache为DiskLruCache
      snapshot = cache.get(key);
      // 如果没有找到
      if (snapshot == null) {
        return null;
      }
    } catch (IOException e) {
      // Give up because the cache cannot be read.
      return null;
    }

    try {
      // 创建entry对象
      entry = new Entry(snapshot.getSource(ENTRY_METADATA));
    } catch (IOException e) {
      Util.closeQuietly(snapshot);
      return null;
    }

    // 得到response对象
    Response response = entry.response(snapshot);

    // 如果请求和响应不匹配
    if (!entry.matches(request, response)) {
      Util.closeQuietly(response.body());
      return null;
    }

    return response;
}

DisLruCache # get()

得到对应key的snapshot

/**
   * Returns a snapshot of the entry named {@code key}, or null if it doesn't exist is not currently
   * readable. If a value is returned, it is moved to the head of the LRU queue.
   */
public synchronized Snapshot get(String key) throws IOException {
    initialize();

    checkNotClosed();
    validateKey(key);
    // 得到相应key的Entry对象
    Entry entry = lruEntries.get(key);
    if (entry == null || !entry.readable) return null;

    // 得到entry的snapshot
    Snapshot snapshot = entry.snapshot();
    if (snapshot == null) return null;

    redundantOpCount++;
    // 更新日志
    journalWriter.writeUtf8(READ).writeByte(' ').writeUtf8(key).writeByte('\n');
    if (journalRebuildRequired()) {
      // 清理线程,用于重建精简日志
      executor.execute(cleanupRunnable);
    }

    return snapshot;
}

Cache # Entry(source)

Okio.source 封装 InputStream,读出缓存文件中的信息保存到Entry

Entry(Source in) throws IOException {
      try {
        BufferedSource source = Okio.buffer(in);
        // 读取请求的相关信息
        url = source.readUtf8LineStrict();
        requestMethod = source.readUtf8LineStrict();
        Headers.Builder varyHeadersBuilder = new Headers.Builder();
        int varyRequestHeaderLineCount = readInt(source);
        for (int i = 0; i < varyRequestHeaderLineCount; i++) {
          varyHeadersBuilder.addLenient(source.readUtf8LineStrict());
        }
        varyHeaders = varyHeadersBuilder.build();

        // 读响应状态行
        StatusLine statusLine = StatusLine.parse(source.readUtf8LineStrict());
        protocol = statusLine.protocol;
        code = statusLine.code;
        message = statusLine.message;
        
        // 读响应首部
        Headers.Builder responseHeadersBuilder = new Headers.Builder();
        int responseHeaderLineCount = readInt(source);
        for (int i = 0; i < responseHeaderLineCount; i++) {
          responseHeadersBuilder.addLenient(source.readUtf8LineStrict());
        }
        String sendRequestMillisString = responseHeadersBuilder.get(SENT_MILLIS);
        String receivedResponseMillisString = responseHeadersBuilder.get(RECEIVED_MILLIS);
        responseHeadersBuilder.removeAll(SENT_MILLIS);
        responseHeadersBuilder.removeAll(RECEIVED_MILLIS);
        sentRequestMillis = sendRequestMillisString != null
            ? Long.parseLong(sendRequestMillisString)
            : 0L;
        receivedResponseMillis = receivedResponseMillisString != null
            ? Long.parseLong(receivedResponseMillisString)
            : 0L;
        responseHeaders = responseHeadersBuilder.build();

        // 如果是https,读握手、证书信息
        if (isHttps()) {
          String blank = source.readUtf8LineStrict();
          if (blank.length() > 0) {
            throw new IOException("expected \"\" but was \"" + blank + "\"");
          }
          String cipherSuiteString = source.readUtf8LineStrict();
          CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
          List<Certificate> peerCertificates = readCertificateList(source);
          List<Certificate> localCertificates = readCertificateList(source);
          TlsVersion tlsVersion = !source.exhausted()
              ? TlsVersion.forJavaName(source.readUtf8LineStrict())
              : TlsVersion.SSL_3_0;
          handshake = Handshake.get(tlsVersion, cipherSuite, peerCertificates, localCertificates);
        } else {
          handshake = null;
        }
      } finally {
        in.close();
      }
}

DisLruCache # Entry

下面是它的成员变量

 private final class Entry {
    final String key;

    /** Lengths of this entry's files. */
    final long[] lengths;
    final File[] cleanFiles;
    final File[] dirtyFiles;

    /** True if this entry has ever been published. */
    boolean readable;

    /** The ongoing edit or null if this entry is not being edited. */
    Editor currentEditor;

    /** The sequence number of the most recently committed edit to this entry. */
    long sequenceNumber;
}

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

Cache.Entry # response()

从缓存中解析出各个字段。当获得这些信息后,就可以用过response() 获得对应的响应

public Response response(DiskLruCache.Snapshot snapshot) {
      // 从Entry中的变量获取
      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();
}

CacheResponseBody

构造方法,获得响应体

 CacheResponseBody(final DiskLruCache.Snapshot snapshot,
        String contentType, String contentLength) {
      this.snapshot = snapshot;
      this.contentType = contentType;
      this.contentLength = contentLength;
      // 获得body的输入流
      Source source = snapshot.getSource(ENTRY_BODY);
      bodySource = Okio.buffer(new ForwardingSource(source) {
        @Override public void close() throws IOException {
          snapshot.close();
          super.close();
        }
      });
}

缓存的使用

OkHttp缓存配置

OkHttpClient # internalCache()

 @Nullable InternalCache internalCache() {
    return cache != null ? cache.internalCache : internalCache;
 }

cache域在我们构造OkHttpClient的时候是没有被初始化的,因此如果我们没有通过调用Builder的cache方法设置cache值的话,该方法返回的对象实际上是一个不支持任何缓存操作的对象(接口),该对象的所有方法为空。因此如果需要OkHttpClient支持缓存,需要我们写一个Cache对象并在构造OkHttpClient的时候将其传给OkHttpClient。

构建cache

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(5, TimeUnit.SECONDS)
        .cache(new Cache(new File(this.getExternalCacheDir(), "okhttpcache"), 10 * 1024 * 1024))
        .build();

OkHttpClient.Builder # cache()

public Builder cache(@Nullable Cache cache) {
      this.cache = cache;
      this.internalCache = null;
      return this;
}

cache的构造方法

FileSystem.SYSTEM是FileSystem接口的一个实现类,该类的各个方法使用Okio对文件I/O进行封装。
DiskLruCache的create()方法中传入的目录将会是缓存的父目录,其中ENTRY_COUNT表示每一个缓存实体中的值的个数(文件),这儿是2。(第一个是请求头部和响应头部,第二个是响应主体部分)

public Cache(File directory, long maxSize) {
    // 文件目录,文件最大大小
    this(directory, maxSize, FileSystem.SYSTEM);
}

Cache(File directory, long maxSize, FileSystem fileSystem) {
    this.cache = DiskLruCache.create(fileSystem, directory, VERSION, ENTRY_COUNT, maxSize);
}

DiskLruCache

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值