okhttp緩存大致內(nèi)容(3.12)

在最近的工作中接觸到了okhttp的緩存,借此機(jī)會(huì)記錄下。網(wǎng)上已經(jīng)有很多相關(guān)文章了,比如參考文章一還包括了http頭緩存的相關(guān)介紹;但是一來自己跟代碼記得比較牢,二來我比較關(guān)心緩存中l(wèi)astModified和etag的設(shè)置所以需要挑重點(diǎn),所以還是自己下手了。
本文基于okhttp 3.12版本

開啟緩存

okhttp開啟緩存非常方便,只需要設(shè)置cache參數(shù)即可

//3mb緩存
final int cacheSize = 1024 * 1024 * 3;
defaultBuilder = new OkHttpClient.Builder()
.cache(new Cache(CmGameSdkConstant.getAppContext().getCacheDir(), cacheSize))
.connectTimeout(DEFAULT_CONNECT_TIME_SEC, TimeUnit.SECONDS);

這樣設(shè)置之后,okhttp就開啟了緩存,包括本地緩存以及瀏覽器相關(guān)緩存(etag、last-modify),這一點(diǎn)我一開始是不信的(原先沒有關(guān)注這方面),看完之后就。。。真香

緩存類Cache內(nèi)部設(shè)置

在第一步中我們開啟了緩存,也就是開啟了cache選項(xiàng),其中傳入了Cache對(duì)象。我們看看這個(gè)對(duì)象做了些什么,首先就是get,這里根據(jù)請(qǐng)求拿到緩存對(duì)應(yīng)的回復(fù),這里是使用LruCache做本地緩存的。

@Nullable Response get(Request request) {
    String key = key(request.url());
    DiskLruCache.Snapshot snapshot;
    Entry entry;
    try {
      snapshot = cache.get(key);
      if (snapshot == null) {
        return null;
      }
    } catch (IOException e) {
      // Give up because the cache cannot be read.
      return null;
    }

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

    Response response = entry.response(snapshot);

    if (!entry.matches(request, response)) {
      Util.closeQuietly(response.body());
      return null;
    }

    return response;
  }

  // 這里是將請(qǐng)求映射為url,使用md5計(jì)算
  public static String key(HttpUrl url) {
    return ByteString.encodeUtf8(url.toString()).md5().hex();
  }

緩存任務(wù)攔截器 CacheInterceptor

在請(qǐng)求流程中,是用鏈?zhǔn)椒职l(fā)的形式走的,大概如下:

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }

其中緩存的關(guān)鍵類就是CacheInterceptor
我們來看看他的攔截關(guān)鍵方法

@Override public Response intercept(Chain chain) throws IOException {
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

一開始根據(jù)請(qǐng)求去獲取緩存的回復(fù)

拿到歷史緩存后,加上當(dāng)前時(shí)間構(gòu)建Request以及Response對(duì)象

long now = System.currentTimeMillis();

CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;

這個(gè)緩存策略CacheStrategy很重要,基本上后面的匹配都與他有關(guān)。這里根據(jù)請(qǐng)求和緩存回復(fù)構(gòu)建,后面關(guān)于http的匹配都是在里面。

在構(gòu)造方法里,我們看到他將解決請(qǐng)求時(shí)間、etag以及l(fā)astModify等信息都保存下來了,為之后的緩存氫氣做準(zhǔn)備

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

//看下Factory的構(gòu)造方法
 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);
          //這里用來保存服務(wù)器時(shí)間,為之后的緩存過期做準(zhǔn)備
          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;
          //表示收到的時(shí)間,同樣是為了后面過期做準(zhǔn)備
          } else if ("Age".equalsIgnoreCase(fieldName)) {
            ageSeconds = HttpHeaders.parseSeconds(value, -1);
          }
        }
      }
    }

隨后我們會(huì)開始構(gòu)建CacheStrategy,也就是緩存策略,緩存會(huì)最終體現(xiàn)在CacheStrategy的networkRequest和cacheResponse中,也就是他的構(gòu)造函數(shù)。最終實(shí)現(xiàn)方法在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.
      // handshake是握手的意思,如果請(qǐng)求為https而且沒有經(jīng)過握手,那也不緩存
      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.
      // 這里是判斷是否不允許緩存,比如返回頭中的no-store,注意這里同步比較了請(qǐng)求和返回的cache策略
      if (!isCacheable(cacheResponse, request)) {
        return new CacheStrategy(request, null);
      }
      
      // 第一個(gè)判斷是請(qǐng)求是否允許緩存,第二個(gè)是請(qǐng)求中如果已經(jīng)帶了If-Modified-Since或者If-None-Match,說明上層自己做了緩存
      CacheControl requestCaching = request.cacheControl();
      if (requestCaching.noCache() || hasConditions(request)) {
        return new CacheStrategy(request, null);
      }

      CacheControl responseCaching = cacheResponse.cacheControl();
      
      //cacheResponseAge 緩存時(shí)間的計(jì)算大概如下
      //return receivedAge + responseDuration + residentDuration;
      //也就是請(qǐng)求到收到時(shí)間+現(xiàn)在使用時(shí)間
      long ageMillis = cacheResponseAge();
      //通過之前緩存的expires、last-modify等計(jì)算緩存有效期
      long freshMillis = computeFreshnessLifetime();
      
      // 如果請(qǐng)求中已經(jīng)包含了max-age,那么我們?nèi)∠鄬?duì)最小值
      if (requestCaching.maxAgeSeconds() != -1) {
        freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
      }
      // Cache-Control相關(guān)    
      // min-fresh是指在期望的時(shí)間內(nèi)響應(yīng)有效
      long minFreshMillis = 0;
      if (requestCaching.minFreshSeconds() != -1) {
        minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
      }

      // 這個(gè)同上,mustRevalidate是指在本地副本未過期前可以使用,否則必須刷新
      long maxStaleMillis = 0;
      if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
        maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
      }

      // 還沒過期,加個(gè)warning信息返回上層,隨即復(fù)用緩存
      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.
      // 這里也有點(diǎn)意思,etag優(yōu)先,然后是If-Modified-Since,然后是服務(wù)器時(shí)間,進(jìn)行拼接,向服務(wù)器請(qǐng)求
      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 {
        // 如果這些都沒有了,那只能走普通的網(wǎng)絡(luò)請(qǐng)求了
        return new CacheStrategy(request, null); // No condition! Make a regular request.
      }
        
      // 最后就是我們的集大成者了,header內(nèi)部是用鍵值對(duì)維護(hù)的
      // 我們重新修改后,生成“附帶屬性”的conditionalRequest
      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);
    }

上面是緩存的大頭,構(gòu)建出了我們想要的內(nèi)容,同時(shí)先過濾一次網(wǎng)絡(luò)請(qǐng)求,如果本地緩存可用則先用本地緩存,這個(gè)時(shí)候request是為空的。

下面我們回到攔截方法CacheInterceptor.intercept

// If we're forbidden from using the network and the cache is insufficient, fail
// 這里是禁止使用網(wǎng)絡(luò)的情況下緩存又無效,所以直接504錯(cuò)誤
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.
    // 如果緩存未過期同時(shí)又沒有網(wǎng)絡(luò),直接返回緩存結(jié)果
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }
    
    // 走到這里說明能用的緩存都用了,還是需要走網(wǎng)絡(luò)的,交給鏈條的下一個(gè)
    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) {
        // 如果是傳說中的304,那么緩存可用,我們主動(dòng)構(gòu)建一個(gè)回復(fù)
        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) {
      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.
        }
      }
    }
    

參考文章

  1. http://www.lxweimin.com/p/00d281c226f6 okhttp緩存處理
  2. https://blog.csdn.net/aiynmimi/article/details/79807036 OkHttp3源碼分析之緩存Cache
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,622評(píng)論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,716評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,746評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,991評(píng)論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,706評(píng)論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,036評(píng)論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,029評(píng)論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,203評(píng)論 0 290
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,725評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,451評(píng)論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,677評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,161評(píng)論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,857評(píng)論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,266評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,606評(píng)論 1 295
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,407評(píng)論 3 400
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,643評(píng)論 2 380

推薦閱讀更多精彩內(nèi)容