Okhttp原始碼閱讀(二)——一個快取是怎麼觸發的

SamanLan發表於2017-12-13

記錄一下知識點(http://www.51testing.com/html/28/116228-238337.html)

Cache-Control 條件GET請求 no-cache only-if-cached
Cache-Control: max-age=31536000, public 伺服器返回:Last-Modified 不使用快取 只使用快取
max-age是有效期 請求帶上:If-Modified-Since 不命中返回503錯誤/網路錯誤
伺服器返回:ETag
請求帶上:If-None-Match

條件GET請求用法: 伺服器返回

Last-Modified: Sat, 4 Aug 2017 09:31:27 GMT
複製程式碼

再次請求帶上

If-Modified-Since: Sat, 4 Aug 2017 09:31:27 GMT
複製程式碼

伺服器會進行判斷,快取可用就只會返回304


伺服器返回

ETag: "1090c1ef-8603"
複製程式碼

再次請求帶上

If-None-Match:"1090c1ef-8603"
複製程式碼

伺服器會進行判斷,快取可用就只會返回304


網摘圖片侵刪-快取機制

下面請開始你的表演 還記得上次的原始碼分析的攔截器鏈嗎,一條完整的攔截器鏈如下

完整的攔截器鏈
見名思義,我們去看CacheIntercept

// 快取
final InternalCache cache;

  public CacheInterceptor(InternalCache cache) {
    this.cache = cache;
  }

  @Override public Response intercept(Chain chain) throws IOException {
// 本次請求的快取
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();

// 快取策略,符合上圖的快取機制。最重要就是裡面的get方法。就好像一棵決策樹,輸入請求和快取響應,輸出決策後的請求和快取響應
    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.
    }

// 和上圖所說的只使用快取並且沒有快取命中,返回504
    // 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());
      }
    }

// Etag或者Last-Modified
    // If we have a cache response too, then we're doing a conditional get.
    if (cacheResponse != null) {
// 伺服器返回304,資料無改變,即可用本地快取,然後更新一下資訊即可
      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) {
// 快取有內容且能夠快取(通過header、剩餘空間等等來判斷)
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
// 存入快取,注意這裡的put裡面也是有判斷的,只有符合的快取條件的才會快取,別以為到put了就一定快取了(例如post請求不快取)。
        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;
  }
複製程式碼

接下來看快取策略的get方法

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

    /** Returns a strategy to use assuming the request can use the network. */
    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);
      }
// 不使用快取或者header帶etag或者if-modify-since
      CacheControl requestCaching = request.cacheControl();
      if (requestCaching.noCache() || hasConditions(request)) {
        return new CacheStrategy(request, null);
      }

// 下面是判斷快取是否失效吧
      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;
      CacheControl responseCaching = cacheResponse.cacheControl();
      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());
      }

// 對快取進行判斷是否有etag或者lastModified ,有得話幫你新增header進request
      // 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);
    }
複製程式碼

得出結論表格,和上圖快取策略一致

networkRequest cacheResponse result
null null only-if-cached(表明不進行網路請求,且快取不存在或者過期,一定會返回503錯誤)
null non-null 不進行網路請求,而且快取可以使用,直接返回快取,不用請求網路
non-null null 需要進行網路請求,而且快取不存在或者過期,或者包含If-Modified-Since或者If-None-Match,則直接訪問網路
non-null non-null Header中含有ETag/Last-Modified標籤,需要在條件請求下使用,還是需要訪問網路

結論表格源於作者:BlackSwift 結束啦-----------(對於ok不進行快取的,下次再說了)

相關文章