源碼分析->撕開OkHttp(8)攔截器CacheInterceptor

源碼分析基于 3.14.4
關(guān)鍵字:攔截器CacheInterceptor

http://www.reibang.com/p/60aaee13ff65上一篇,講了CallServerInterceptor攔截器的作用菜谣。

這次分析CacheInterceptor

緩存攔截,顧名思義就是做緩存處理的归榕。

還是看CacheInterceptor.intercept

(1)說實(shí)在話全闷,緩存的邏輯比較復(fù)雜漂问,我也不是每個細(xì)節(jié)都看懂了,只知道個大概震糖;
(2)cache.get(chain.request())录肯,根據(jù)url的MD5值獲取緩存cacheCandidate ,candidate是候選的意思吊说,表示可能會返回這個论咏;
(3)new CacheStrategy.Factory,根據(jù)Request颁井、Response 厅贪、當(dāng)前時間創(chuàng)建緩存策略CacheStrategy ,這里面是對能否使用緩存做邏輯處理雅宾,后面會重點(diǎn)分析养涮;
(4)networkRequest 表示請求實(shí)體,cacheResponse 表示緩存實(shí)體眉抬,兩者共同決定使用請求還是緩存贯吓;
(5)無請求且無緩存,則networkRequest == null && cacheResponse == null成立蜀变,構(gòu)建504Response返回悄谐,通常發(fā)生在客戶端只希望使用緩存,請求頭帶only-if-cached的情況;
(6)無請求库北,則networkRequest == null條件成立爬舰,直接返回緩存;
(7)添加(6)不成立贤惯,即有請求洼专,則調(diào)用后續(xù)攔截器發(fā)起請求;
(8)后續(xù)攔截器返回孵构,即服務(wù)器返回結(jié)果屁商,有緩存且服務(wù)器返回304(表示內(nèi)容沒有變化,可以用緩存)颈墅,則networkResponse.code() == HTTP_NOT_MODIFIED條件成立蜡镶,更新緩存的發(fā)起請求時間、接收響應(yīng)時間恤筛、緩存響應(yīng)官还、網(wǎng)絡(luò)響應(yīng),最后返回毒坛;
(9)不是返回304望伦,響應(yīng)有body且可以緩存林说,例如返回200且請求頭不帶no-store且響應(yīng)頭不帶no-store,則HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)條件成立屯伞,把響應(yīng)緩存起來并返回腿箩;
(10)如果請求是POST、DELETED的劣摇,刪除緩存珠移;
(11)條件(9)不成立,則直接返回響應(yīng)末融;

 @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 (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 (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }
 ......
 networkResponse = chain.proceed(networkRequest);
......
    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();

        cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } 
    ......
    }

    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
         cache.remove(networkRequest);
         ......
      }
    }
    return response;
  }
流程1.png
看下構(gòu)建緩存策略是如何處理networkRequest 以及cacheResponse的钧惧,主要看CacheStrategy.Factory構(gòu)造方法以及get方法;

先看CacheStrategy.Factory構(gòu)造方法勾习,
主要是構(gòu)建緩存策略構(gòu)造浓瞪,獲取緩存發(fā)起時間(即發(fā)起請求時間)、緩存接收數(shù)據(jù)语卤、讀取跟緩存相關(guān)的請求頭(Date追逮、Expires、Last-Modified等)粹舵;

    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);
          }
        }
      }
    }
CacheStrategy.Factory.get

(1)getCandidate()钮孵,獲取候選緩存策略;
(2)如果networkRequest 不為空且請求頭包含only-if-cached眼滤,則把構(gòu)建一個networkRequest以及cacheResponse為空的緩存策略巴席;

    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;
    }
CacheStrategy.Factory.getCandidate

(1)這個方法有點(diǎn)長,主要是獲取各種時間計算诅需;
(2)如果是HTTPS請求但是握手信息為空漾唉,則request.isHttps() && cacheResponse.handshake()條件成立,返回cacheResponse為空的緩存策略堰塌;
(3)如果緩存不應(yīng)該被緩存的赵刑,則!isCacheable(cacheResponse, request)條件成立,同樣返回cacheResponse為空的緩存策略场刑,例如cacheResponse返回碼不是200般此、獲取請求頭帶no-store、或者cacheResponse頭帶no-store牵现;
(4)如果請求不使用緩存铐懊、或者需要詢問服務(wù)器是否可以使用緩存,則返回cacheResponse為空的緩存策略瞎疼,例如請求頭帶no-cache科乎、If-Modified-Since、If-None-Match贼急;
(5)cacheResponseAge茅茂,計算緩存年齡捏萍;
(6)computeFreshnessLifetime,計算緩存新鮮度玉吁;
(7)如果緩存沒有過有效期照弥,則ageMillis + minFreshMillis < freshMillis + maxStaleMillis條件成立腻异,返回networkRequest 為空而cacheResponse不為空的緩存策略进副,表示直接使用緩存;
(8)如果緩存頭包含ETag悔常、Last-Modified影斑、Date其中一個請求頭,則返回networkRequest 不為空而cacheResponse為空緩存策略机打,表示需要請求服務(wù)器矫户;
(9)條件(8)不成立,則返回networkRequest 且cacheResponse不為空的緩存策略残邀,表示需要跟服務(wù)器協(xié)商皆辽,這個緩存能不能使用;

    private CacheStrategy getCandidate() {
      ......
      if (request.isHttps() && cacheResponse.handshake() == null) {
        return new CacheStrategy(request, null);
      }
      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.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
       ......
        return new CacheStrategy(null, builder.build());
      }
      ......
      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);
    }
總結(jié)

(1)CacheInterceptor緩存攔截芥挣,顧名思義就是做緩存處理的;
(2)OkHttp默認(rèn)支持緩存驱闷,配置OkHttpClient.cahe就可以開啟緩存,只要服務(wù)器做相應(yīng)處理空免;
(3)只緩存GET請求空另;
(4)緩存策略中的networkRequest 以及cacheResponse決定是否使用緩存;
networkRequest 蹋砚、cacheResponse兩者為空扼菠,表示客戶端只希望使用緩存only-if-cached,返回504響應(yīng)坝咐;
networkRequest 為空循榆,cacheResponse不為空,則返回緩存墨坚;
networkRequest 不為空秧饮,cacheResponse為空,則沒有緩存可以使用框杜,需要請求服務(wù)器浦楣;
networkRequest 瘩将、cacheResponse兩者都不為空弛槐,則需要跟服務(wù)器協(xié)商,過去緩存能不能使用苇侵。

以上分析有不對的地方油狂,請指出历恐,互相學(xué)習(xí)寸癌,謝謝哦!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末弱贼,一起剝皮案震驚了整個濱河市蒸苇,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吮旅,老刑警劉巖溪烤,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異庇勃,居然都是意外死亡檬嘀,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進(jìn)店門责嚷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鸳兽,“玉大人,你說我怎么就攤上這事罕拂∽嵋欤” “怎么了?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵爆班,是天一觀的道長衷掷。 經(jīng)常有香客問我,道長蛋济,這世上最難降的妖魔是什么棍鳖? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮碗旅,結(jié)果婚禮上渡处,老公的妹妹穿的比我還像新娘。我一直安慰自己祟辟,他們只是感情好医瘫,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著旧困,像睡著了一般醇份。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上吼具,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天僚纷,我揣著相機(jī)與錄音,去河邊找鬼拗盒。 笑死怖竭,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的陡蝇。 我是一名探鬼主播痊臭,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼哮肚,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了广匙?” 一聲冷哼從身側(cè)響起允趟,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎鸦致,沒想到半個月后潮剪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蹋凝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年鲁纠,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鳍寂。...
    茶點(diǎn)故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖情龄,靈堂內(nèi)的尸體忽然破棺而出迄汛,到底是詐尸還是另有隱情,我是刑警寧澤骤视,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布鞍爱,位于F島的核電站,受9級特大地震影響专酗,放射性物質(zhì)發(fā)生泄漏睹逃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一祷肯、第九天 我趴在偏房一處隱蔽的房頂上張望沉填。 院中可真熱鬧,春花似錦佑笋、人聲如沸翼闹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽猎荠。三九已至,卻和暖如春蜀备,著一層夾襖步出監(jiān)牢的瞬間关摇,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工碾阁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留输虱,地道東北人。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓瓷蛙,卻偏偏與公主長得像悼瓮,于是被迫代替她去往敵國和親戈毒。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,974評論 2 355

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