OkHttp的CacheInterceptor緩存攔截器剖析

OkHttp的橋攔截器的源碼解讀傳送門:http://www.lxweimin.com/p/20bfab62c3cd
OkHttp有自己的一套緩存,其實最終還是使用DiskLruCache進行緩存,通過Okhttp內部的線程池對緩存進行保存清除等操作的。

/** Serves requests from the cache and writes responses to the cache.
 *
 *  服務來自緩存的請求并將響應寫入緩存
 */
public final class CacheInterceptor implements Interceptor {
    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();

        // 緩存策略 可以設置從緩存中取,也可以設置從網絡取,也可以同時設置兩者都使用
        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.
        // 當前不能使用網絡,也沒有找到相應的緩存,這時候會構造出一個Response,拋出一個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.
        // 有緩存,不能使用網絡,直接返回緩存的結果
        if (networkRequest == null) {
            return cacheResponse.newBuilder()
                    .cacheResponse(stripBody(cacheResponse))
                    .build();
        }

        Response networkResponse = null;
        try {
            // 通過調用攔截器的方法進行網絡請求獲取,具體的網絡工作交給下一個攔截器來做的,下一個攔截器其實就是ConnectInterceptor
            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.
        // 接收到網絡結果,如果響應code式304,則使用緩存,返回緩存結果
        if (cacheResponse != null) {
            if (networkResponse.code() == HTTP_NOT_MODIFIED) { // 返回的code為304時,表示得從緩存中獲取
                        .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;
    }

緩存的存取都是在這個類Cache中操作的:
Cache緩存請求數據和響應數據,通過內部類CacheRequestImpl來實現CacheInterceptor緩存攔截器的緩存的寫入讀取操作。
get方法:

/**
     * 獲取響應體數據的方法
     * @param request
     * @return
     */
    @Nullable Response get(Request request) {
        String key = key(request.url());
        // 最終還是使用DiskLruCache進行緩存,通過Okhttp內部的線程池對緩存進行保存清除等操作的
        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;
    }

涉及到的key方法:

 // 對請求的url進行md5處理,并進行16進制轉換
    public static String key(HttpUrl url) {
        return ByteString.encodeUtf8(url.toString()).md5().hex();
    }

put方法:

/**
     * 緩存存入數據的方法
     * @param response
     * @return
     */
    @Nullable CacheRequest put(Response response) {
        String requestMethod = response.request().method();

        if (HttpMethod.invalidatesCache(response.request().method())) {
            try {
                remove(response.request());
            } catch (IOException ignored) {
                // The cache cannot be written.
            }
            return null;
        }
        if (!requestMethod.equals("GET")) { // Get請求
            // Don't cache non-GET responses. We're technically allowed to cache
            // HEAD requests and some POST requests, but the complexity of doing
            // so is high and the benefit is low.
            return null;
        }

        if (HttpHeaders.hasVaryAll(response)) {
            return null;
        }

        // 需要緩存的實體,這里面封裝了所需要緩存的所有內容
        Entry entry = new Entry(response);
        DiskLruCache.Editor editor = null;
        try {
            editor = cache.edit(key(response.request().url()));
            if (editor == null) {
                return null;
            }
            entry.writeTo(editor); // 開始真正緩存
            return new CacheRequestImpl(editor); // 通過這個接口來實現緩存攔截器的緩存的寫入都去操作
        } catch (IOException e) {
            abortQuietly(editor);
            return null;
        }
    }

謝謝閱讀,如有錯誤,歡迎指正。

OkHttp的ConnectInterceptor連接攔截器剖析:http://www.lxweimin.com/p/f90aa5894cdf

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。