OKHTTP源码分析-CacheInterceptor

有了前面两章的分析小伙伴们应该对我们的okhttp拦截器有了比较清晰地认识了这次我们介绍一个重量级的拦截器CacheInterceptor顾名思义这个拦截器是处理我们请求缓存的加入我们请求设置了缓存走到这里后会优先调用缓存而不会走网络,那我们就二话不说上代码吧。

@Override public Response intercept(Chain chain) throws IOException {
    // 从缓存里面拿,到底怎么拿?放一边
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();
    // 构建了一个缓存策略
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    // networkRequest 还不知道是啥 networkRequest 做了处理
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;

    if (cache != null) {
      cache.trackResponse(strategy);
    }

    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    }

    // If we're forbidden from using the network and the cache is insufficient, fail.
    // 如果请求的 networkRequest 是空,缓存的 cacheResponse 是空我就返回 504
    // 指定该数据只从缓存获取,一般不会这么傻
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }

    // If we don't need the network, we're done.
    if (networkRequest == null) {
      // 如果缓存策略里面的 networkRequest 是空,那么就 返回 缓存好的 Response
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

    Response networkResponse = null;
    try {
      // 否则的话给下面
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

    // If we have a cache response too, then we're doing a conditional get.
    // 处理返回,处理 304 的情况
    if (cacheResponse != null) {
      if (networkResponse.code() == HTTP_NOT_MODIFIED) {
        // 服务器数据没有变化,你还是可以拿之前的缓存
        Response response = cacheResponse.newBuilder()
            .headers(combine(cacheResponse.headers(), networkResponse.headers()))
            .sentRequestAtMillis(networkResponse.sentRequestAtMillis())
            .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
        networkResponse.body().close();

        // Update the cache after combining headers but before stripping the
        // Content-Encoding header (as performed by initContentStream()).
        cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } else {
        closeQuietly(cacheResponse.body());
      }
    }
    // 要返回 response
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      // 然后缓存获取的 Response
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }

    return response;
  }

我们依然是逐行分析,Response cacheCandidate = cache != null ? cache.get(chain.request()) : null;这行的意思很明显如果我们的cache 不为空那么久从cache中取数据如果为空那么直接返回null当然我们的缓存是根据request去取得。之后就是构建一个缓存策略从缓存策略。

  CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();

我们先看它里面的Factory是什么东西

    public Factory(long nowMillis, Request request, Response cacheResponse) {
      this.nowMillis = nowMillis;
      this.request = request;
      this.cacheResponse = cacheResponse;

      if (cacheResponse != null) {

        this.sentRequestMillis = cacheResponse.sentRequestAtMillis();
        this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis();
        Headers headers = cacheResponse.headers();
        for (int i = 0, size = headers.size(); i < size; i++) {
          String fieldName = headers.name(i);
          String value = headers.value(i);
          // 解析之前缓存好的一些头部信息,服务器给的 Expires 缓存的过去时间,Last-Modified 服务器上次数据的更新时间
          if ("Date".equalsIgnoreCase(fieldName)) {
            servedDate = HttpDate.parse(value);
            servedDateString = value;
          } else if ("Expires".equalsIgnoreCase(fieldName)) {
            expires = HttpDate.parse(value);
          } else if ("Last-Modified".equalsIgnoreCase(fieldName)) {
            lastModified = HttpDate.parse(value);
            lastModifiedString = value;
          } else if ("ETag".equalsIgnoreCase(fieldName)) {
            etag = value;
          } else if ("Age".equalsIgnoreCase(fieldName)) {
            ageSeconds = HttpHeaders.parseSeconds(value, -1);
          }
        }
      }
    }

这个方法的作用是把之前的发送接收时间,当前时间,等等等等放入全局变量,等待下一步操作,我们继续看下一步操作。

 public CacheStrategy get() {
      CacheStrategy candidate = getCandidate();
      // onlyIfCached 只能从缓存里面获取
      // networkRequest = null cacheResponse = null
      if (candidate.networkRequest != null && request.cacheControl().onlyIfCached()) {
        // We're forbidden from using the network and the cache is insufficient.
        return new CacheStrategy(null, null);
      }

      return candidate;
    }

上面的代码意思上很好理解取出缓存来然后判断是不是只从缓存中取数据,最后将缓存返回这里面最重要的是getCandidate这个方法我们接下来看okhttp是如何从缓存里面那数据的。

private CacheStrategy getCandidate() {
      // No cached response.
      if (cacheResponse == null) {
        return new CacheStrategy(request, null);
      }

      // Drop the cached response if it's missing a required handshake.
      if (request.isHttps() && cacheResponse.handshake() == null) {
        return new CacheStrategy(request, null);
      }

      // If this response shouldn't have been stored, it should never be used
      // as a response source. This check should be redundant as long as the
      // persistence store is well-behaved and the rules are constant.
      // 要不要缓存,缓存策略,Public、private、no-cache、max-age
      if (!isCacheable(cacheResponse, request)) {
        return new CacheStrategy(request, null);
      }

      CacheControl requestCaching = request.cacheControl();
      if (requestCaching.noCache() || hasConditions(request)) {
        return new CacheStrategy(request, null);
      }

      CacheControl responseCaching = cacheResponse.cacheControl();
      if (responseCaching.immutable()) {
        return new CacheStrategy(null, cacheResponse);
      }
      // 缓存策略 + 过期时间
      long ageMillis = cacheResponseAge();
      long freshMillis = computeFreshnessLifetime();
      if (requestCaching.maxAgeSeconds() != -1) {
        freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
      }
      long minFreshMillis = 0;
      if (requestCaching.minFreshSeconds() != -1) {
        minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
      }
      long maxStaleMillis = 0;
      if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
        maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
      }

      if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
        Response.Builder builder = cacheResponse.newBuilder();
        if (ageMillis + minFreshMillis >= freshMillis) {
          builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
        }
        long oneDayMillis = 24 * 60 * 60 * 1000L;
        if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
          builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
        }
        // 如果缓存没有过期并且需要缓存 那么 networkRequest = null cacheResponse = 缓存好的
        return new CacheStrategy(null, builder.build());
      }

      // 本地有缓存,并且缓存已经过去,那么需要把上一次的请求头的一些字段带过去 If-Modified-Since
      // 请求 -> 返回 -> 更新时间
      // 请求(If-Modified-Since) -> 比对(304)

      // Find a condition to add to the request. If the condition is satisfied, the response body
      // will not be transmitted.
      String conditionName;
      String conditionValue;
      if (etag != null) {
        conditionName = "If-None-Match";
        conditionValue = etag;
      } else if (lastModified != null) {
        conditionName = "If-Modified-Since";
        conditionValue = lastModifiedString;
      } else if (servedDate != null) {
        conditionName = "If-Modified-Since";
        conditionValue = servedDateString;
      } else {
        return new CacheStrategy(request, null); // No condition! Make a regular request.
      }

      Headers.Builder conditionalRequestHeaders = request.headers().newBuilder();
      Internal.instance.addLenient(conditionalRequestHeaders, conditionName, conditionValue);

      Request conditionalRequest = request.newBuilder()
          .headers(conditionalRequestHeaders.build())
          .build();
      return new CacheStrategy(conditionalRequest, cacheResponse);
    }

果然是一段很长的代码,别急我们逐行分析

//没有缓存直接将CacheResponse设置为空 返回进行直接连接
 if (cacheResponse == null) {
        return new CacheStrategy(request, null);
      }

这个很简单吧,没缓存我们就把缓存响应即CacheResponse设置为空返回,继续看

// 如果缓存的TLS握手信息丢失,将CacheResponse设置为空 返回进行直接连接
  if (request.isHttps() && cacheResponse.handshake() == null) {
    return new CacheStrategy(request, null);
  }

是不是很easy啊我们接下来看

 // 要不要缓存,缓存策略,Public、private、no-cache、max-age
      if (!isCacheable(cacheResponse, request)) {
        return new CacheStrategy(request, null);
      }

isCacheable这个方法是根据response.code()进行判断是不是可以做缓存部分responsecode不能做缓存需要处理,最好返回的是如果请求可以缓存响应也可以缓存则返回true,我们接着看下面的。

 CacheControl requestCaching = request.cacheControl();
     //有ETag/Since标签
      if (requestCaching.noCache() || hasConditions(request)) {
        return new CacheStrategy(request, null);
      }

上面一段的意思是 如果没有缓存或者,If-Modified-Since标签或者If-None-Match标签获取不到则走网络请求不走缓存,至于这两个标签是什么意思大致意思是服务器做缓存的标签If-Modified-Since指服务器文件最后修改时间,后面那个不清楚了想了解的童鞋可以查查资料。

// 缓存策略 + 过期时间
      long ageMillis = cacheResponseAge();
      long freshMillis = computeFreshnessLifetime();
      if (requestCaching.maxAgeSeconds() != -1) {
        freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
      }
      long minFreshMillis = 0;
      if (requestCaching.minFreshSeconds() != -1) {
        minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
      }
      long maxStaleMillis = 0;
      if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
        maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
      }

      if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
        Response.Builder builder = cacheResponse.newBuilder();
        if (ageMillis + minFreshMillis >= freshMillis) {
          builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
        }
        long oneDayMillis = 24 * 60 * 60 * 1000L;
        if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
          builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
        }
        // 如果缓存没有过期并且需要缓存 那么 networkRequest = null cacheResponse = 缓存好的
        return new CacheStrategy(null, builder.build());
      }

这块的意思是当我们设置的缓存时间没有过期且需要做缓存处理那返回将网络缓存置为空本地缓存添加进去。
最终回到我们的intercept中去

  CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();

我们通过上面的一系列的处理返回了缓存的策略,缓存策略包括两部分一部分走网络一部分走本地缓存。

    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    }

我们接下来分析当缓存不适用的时候关闭它(cacheResponse 为空则不是我们需要的缓存)

 // If we're forbidden from using the network and the cache is insufficient, fail.
    // 如果请求的 networkRequest 是空,缓存的 cacheResponse 是空我就返回 504
    // 指定该数据只从缓存获取,一般不会这么傻
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }

这部分注释写的很清晰了如果本地网络策略都为空那么返回504错误。接下来就清晰了肯定是对networkRequest 及cacheResponse 的分部判断

 // If we don't need the network, we're done.
    if (networkRequest == null) {
      // 如果缓存策略里面的 networkRequest 是空,那么就 返回 缓存好的 Response
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

请求策略不走网络那直接去取缓存,并返回处理结果。
否则给下面的链条去处理丢给下一层拦截器。

Response networkResponse = null;
    try {
      // 否则的话给下面
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

等待其他后面的拦截器处理完成后执行下面的代码

// If we have a cache response too, then we're doing a conditional get.
    // 处理返回,处理 304 的情况
    if (cacheResponse != null) {
      if (networkResponse.code() == HTTP_NOT_MODIFIED) {
        // 服务器数据没有变化,你还是可以拿之前的缓存
        Response response = cacheResponse.newBuilder()
            .headers(combine(cacheResponse.headers(), networkResponse.headers()))
            .sentRequestAtMillis(networkResponse.sentRequestAtMillis())
            .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
        networkResponse.body().close();

        // Update the cache after combining headers but before stripping the
        // Content-Encoding header (as performed by initContentStream()).
        cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } else {
        closeQuietly(cacheResponse.body());
      }
    }

如果返回结果为304则只需要将之前的缓存取出来返回并最终关闭缓存体

// 要返回 response
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      // 然后缓存获取的 Response
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }

    return response;

最终组装响应如果我们的响应可以缓存则将返回信息保存到缓存中去,返回响应完成任务。

猜你喜欢

转载自blog.csdn.net/u011048906/article/details/79585028