okhttp之CacheInterceptor

CacheInterceptor是okhttp中缓存拦截器,是负责http请求的缓存处理。当从上个拦截器中获取到http请求时,会从缓存里面取出对应的响应(之前缓存过的),如果没有,返回null。然后会根据request和获取到的缓存的response生成一个缓存策略CacheStrategy。

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

这个缓存策略决定了获取到的缓存response能不能用,需不需要重新去服务器请求数据。看代码:

    //从缓存策略中获取到网络请求体(如果缓存不可用,需要用这个Request向服务器请求数据)
    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.
    //如果网络请求和缓存响应都为空,表示只允许使用缓存但是缓存不存在
    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) {
      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());
      }
    }

获取到CacheStrategy实体后,全部是根据cacheStrategy中的response和request来判断是否需要去服务器请求数据的。分为这么几种情况:

1、当response==null&&request==null时,表示只读取缓存数据,但是缓存数据为空,这时返回一个code为504的响应体

2、当request==null&&response!=null,表示缓存策略不希望去服务器请求数据,缓存数据完全可用。

3、当request!=null&&response!=null,表示缓存策略可能不存在或者不可用,那么就把请求发送到下个拦截器中进行网络请求
从上面的代码中可以看出,是否需要进行网络请求、缓存是否能用完全取决于缓存策略。缓存策略才是核心。

从后面的拦截器中获取到响应后,需要对响应进行存储,以便下次发起请求时可以直接利用缓存信息。

    // If we have a cache response too, then we're doing a conditional get.
    //如果缓存响应存在
    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 = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      //当存在响应体并且可以缓存,
      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;
}

保存缓存的逻辑就比较简单了,主要分两种情况:

第一种情况,缓存已经存在,如果服务器返回的code为304,表示返回的内容没用修改,那就把已用的缓存和网络响应合并然后进行更新缓存。

第二种情况,缓存不存在或者服务器返回的内容发生了改变,在需要缓存的情况下把网络响应内容进行保存

保存缓存的逻辑到这里就结束了,下面来看缓存策略是怎么生成的。生成缓存策略的代码如下

/**
 * Returns a strategy to satisfy {@code request} using the a cached response {@code response}.
 */
public CacheStrategy get() {
  //获取缓存策略
  CacheStrategy candidate = getCandidate();
  //只允许使用缓存
  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()方法中

 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.
        // https,但是没有进行握手,进行网络请求,不使用缓存
      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.
      //如果不允许使用缓存(请求中不允许或者响应体中不允许使用缓存)
      if (!isCacheable(cacheResponse, request)) {
        return new CacheStrategy(request, null);
      }

      CacheControl requestCaching = request.cacheControl();
      if (requestCaching.noCache() || hasConditions(request)) {
        //请求头nocache或者请求头包含If-Modified-Since或者If-None-Match
        //请求头包含If-Modified-Since或者If-None-Match意味着本地缓存过期,需要服务器验证
        //本地缓存是不是还能继续使用
        return new CacheStrategy(request, null);
      }

      CacheControl responseCaching = cacheResponse.cacheControl();
      if (responseCaching.immutable()) {
        return new CacheStrategy(null, cacheResponse);
      }
      //缓存age
      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\"");
        }
        //缓存可用,返回Response可用的缓存策略
        return new CacheStrategy(null, builder.build());
      }

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

生成cacheStrategy对象的核心就在于request和response的赋值。对这两个变量的赋值主要分为几种情况:

1、缓存为空,那么就需要进行网络请求,所以只给request赋值,response为空

2、是https请求,但是还没有经过握手,这样缓存也不能用,所以只给request赋值,response为空

3、不允许使用缓存(请求中不允许或者响应体中不允许使用缓存),只给request赋值,response为空

4、请求头nocache或者请求头包含If-Modified-Since或者If-None-Match 表示缓存已经过期,需要重新请求服务器看响应内容是否有改变,只给request赋值,response为空

5、缓存过期 这里又分为两种情况。第一种,缓存response的头部含有ETag、Date、Last-Modified中的至少一个,就为请求头加上以下代码中标记,并且给request赋值,同时给response赋值为缓存的response。第二种情况 如果缓存response的头部不含有这些标记值,那么只给request赋值,response为空

     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;

到这里,整个缓存策略的核心就介绍完了,根据返回的request和response使拦截器判断是否使用缓存。

    原文作者:黑猫警长_01
    原文地址: https://www.jianshu.com/p/d1a47aff0bd6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞