工作生活

okhttp4

2019-08-12  本文已影响0人  天马呵呵拳

okhttp分享四:CacheInterceptor

在介绍okhttp缓存逻辑实现之前,首先我们介绍下http缓存相关知识

一、HTTP缓存介绍

1.1、 为什么要用缓存

1、减少请求次数,较少服务器压力
2、本地数据读取更快,让页面不会空白几百毫秒
3、在无网络的情况下提供数据 HTTP缓存是最好的减少客户端服务器往返次数的方案,缓存提供了一种机制来保证客户端或者代理能够存储一些东西,而这些东西将会在稍后的HTTP响应中用到的。(即第一次请求了,到了客户端,缓存起来,下次如果请求还需要一些资源,就不用到服务器去取了)这样,就不用让一些资源再次跨越整个网络了。


缓存1.png

1.2、缓存分类

按照是否向直接服务器发起请求进行对比分类,可以分为两类,即强制缓存和对比缓存。
1、强制缓存
已存在缓存数据时,强制缓存由请求头中Cache-Control字段控制,仅基于强制缓存,请求数据流程如下:


缓存2.png

2、对比缓存缓存
已存在缓存数据时,对比缓存由请求头中ETag/If-None-Match,Last-Modified/If-Modified-Since四个字段控制。仅基于对比缓存,请求数据流程如下:


缓存3.png
3、整体流程
缓存4.png

1.3、http协议强制缓存对应字段

1.4、http协议对比缓存对应字段

1.5、HTTP请求的幂等性

HTTP方法的幂等性是指一次和多次请求某一个资源应该具有同样的副作用。说白了就是,同一个请求,发送一次和发送N次效果是一样的。
各个方法中,get、head、delete、option、put是幂等的,connect、methods、post、patch是非幂等的。我们主要关注get和post。若按照RFC协议规范,对于仅是查询,不改变服务器资源的请求应当使用get,而要改变服务器资源的请求应当使用post,与此对应Http协议的缓存以及重定向主要都是针对get的。

二、CacheControl,CacheStrategy,CacheInterceptor

okhttp实现缓存主要依靠CacheControl,CacheStrategy,CacheInterceptor三个类
http缓存逻辑实现大致分为三种
1、本地无缓存命中,直接走网络
2、有缓存命中且未过期,直接返回
3、有缓存命中,但缓存过期,走网络
接下来我们来分析代码

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

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

介绍逻辑前先解释下几个参数
Response cacheCandidate:根据用户请求从本地缓存中取出的对应缓存响应(不一定使用),为空表示客户端未分配缓存。
CacheStrategy strategy:缓存策略,包含一个网络请求networkRequest(为空时表示不需要网络请求,不为空表示需要发送网络请求),cacheResponse(为空表示cacheCandidate不符合条件,不使用)。下面开始解释代码逻辑

大致流程说完后,我们再来看下流程第2步中CacheStrategy的生成过程CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();

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

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

可以看出,其初始化方法主要是给一些字段赋值,具体参数意义之前介绍字段时已经说过,这边就不再赘述。get方法实际上是调用了getCandidate()方法返回一个CacheStrategy,之后判断若CacheStrategy中的networkRequest不为null但请求配置为onlyIfCached,则说明用户配置只能使用缓存但缓存并不满足条件,因此更新CacheStrategy,将其networkRequest及cacheResponse都置空。

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.
      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\"");
        }
        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);
    }
    
    ···
public static boolean isCacheable(Response response, Request request) {
    // Always go to network for uncacheable response codes (RFC 7231 section 6.1),
    // This implementation doesn't support caching partial content.
    switch (response.code()) {
      case HTTP_OK://200
      case HTTP_NOT_AUTHORITATIVE://203
      case HTTP_NO_CONTENT://204
      case HTTP_MULT_CHOICE://300
      case HTTP_MOVED_PERM://301
      case HTTP_NOT_FOUND://404
      case HTTP_BAD_METHOD://405
      case HTTP_GONE://410
      case HTTP_REQ_TOO_LONG://414
      case HTTP_NOT_IMPLEMENTED://501
      case StatusLine.HTTP_PERM_REDIRECT://308
        // These codes can be cached unless headers forbid it.
        break;

      case HTTP_MOVED_TEMP://302
      case StatusLine.HTTP_TEMP_REDIRECT://307
        // These codes can only be cached with the right response headers.
        // http://tools.ietf.org/html/rfc7234#section-3
        // s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage.
        if (response.header("Expires") != null
            || response.cacheControl().maxAgeSeconds() != -1
            || response.cacheControl().isPublic()
            || response.cacheControl().isPrivate()) {
          break;
        }
        // Fall-through.

      default:
        // All other codes cannot be cached.
        return false;
    }

    // A 'no-store' directive on request or response prevents the response from being cached.
    return !response.cacheControl().noStore() && !request.cacheControl().noStore();
  }

getCandidate方法是根据传入的当前请求request判断,缓存响应cacheResponse是否过期,其逻辑如下

/**
     * Returns true if the request contains conditions that
    save the server from sending a response
    * that the client has locally. When a request is enqueued with its own conditions, the built-in

     * response cache won't be used.
     */
    private static boolean hasConditions(Request request) {
      return request.header("If-Modified-Since") != null || request.header("If-None-Match") != null;
    }

大致逻辑已经讲完,整理了一张图,供大家参考

okhttp缓存策略.jpeg
上一篇 下一篇

猜你喜欢

热点阅读