okhttp之旅(六)--CacheInterceptor緩存攔截器

系統(tǒng)學(xué)習(xí)詳見OKhttp源碼解析詳解系列

1 述

Okhttp是有自己的一套緩存機(jī)制的,CacheInterceptor就是用來負(fù)責(zé)讀取緩存以及更新緩存的。
提供來自緩存的請求并將響應(yīng)寫入緩存

2 整個(gè)方法的流程如下所示:

  • 1.讀取候選緩存,具體如何讀取的我們下面會(huì)講。
    1. 創(chuàng)建緩存策略,強(qiáng)制緩存、對比緩存等,關(guān)于緩存策略我們下面也會(huì)講。
  • 3.根據(jù)策略,不使用網(wǎng)絡(luò),又沒有緩存的直接報(bào)錯(cuò),并返回錯(cuò)誤碼504。
  • 4.根據(jù)策略,不使用網(wǎng)絡(luò),有緩存的直接返回。
  • 5.前面兩個(gè)都沒有返回,繼續(xù)執(zhí)行下一個(gè)Interceptor,即ConnectInterceptor。
  • 6.接收到網(wǎng)絡(luò)結(jié)果,如果響應(yīng)code式304,則使用緩存,返回緩存結(jié)果。
  • 7.讀取網(wǎng)絡(luò)結(jié)果。
  • 8.對數(shù)據(jù)進(jìn)行緩存。
  • 9.返回網(wǎng)絡(luò)讀取的結(jié)果。

3 代碼

public final class CacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //1. 讀取候選緩存
        Response cacheCandidate = cache != null
                ? cache.get(chain.request())
                : null;

        long now = System.currentTimeMillis();
        //2. 創(chuàng)建緩存策略,強(qiáng)制緩存、對比緩存等
        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.
        //3. 根據(jù)策略,不使用網(wǎng)絡(luò),又沒有緩存的直接報(bào)錯(cuò),并返回錯(cuò)誤碼504。
        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.
        //4. 根據(jù)策略,不使用網(wǎng)絡(luò),有緩存的直接返回。
        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.
            // 5. 前面兩個(gè)都沒有返回,繼續(xù)執(zhí)行下一個(gè)Interceptor,即ConnectInterceptor。
            if (networkResponse == null && cacheCandidate != null) {
                closeQuietly(cacheCandidate.body());
            }
        }

        // If we have a cache response too, then we're doing a conditional get.
        //6. 接收到網(wǎng)絡(luò)結(jié)果,如果響應(yīng)code式304,則使用緩存,返回緩存結(jié)果。
        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());
            }
        }
        //7. 讀取網(wǎng)絡(luò)結(jié)果。
        Response response = networkResponse.newBuilder()
                .cacheResponse(stripBody(cacheResponse))
                .networkResponse(stripBody(networkResponse))
                .build();
        //8. 對數(shù)據(jù)進(jìn)行緩存。
        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);
            }
            //9. 返回網(wǎng)絡(luò)讀取的結(jié)果。
            if (HttpMethod.invalidatesCache(networkRequest.method())) {
                try {
                    cache.remove(networkRequest);
                } catch (IOException ignored) {
                    // The cache cannot be written.
                }
            }
        }

        return response;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容