美文网首页
okhttp之旅(六)--CacheInterceptor缓存拦

okhttp之旅(六)--CacheInterceptor缓存拦

作者: brock | 来源:发表于2019-01-31 15:14 被阅读67次

    1 述

    Okhttp是有自己的一套缓存机制的,CacheInterceptor就是用来负责读取缓存以及更新缓存的。
    提供来自缓存的请求并将响应写入缓存

    2 整个方法的流程如下所示:

    • 1.读取候选缓存,具体如何读取的我们下面会讲。
      1. 创建缓存策略,强制缓存、对比缓存等,关于缓存策略我们下面也会讲。
    • 3.根据策略,不使用网络,又没有缓存的直接报错,并返回错误码504。
    • 4.根据策略,不使用网络,有缓存的直接返回。
    • 5.前面两个都没有返回,继续执行下一个Interceptor,即ConnectInterceptor。
    • 6.接收到网络结果,如果响应code式304,则使用缓存,返回缓存结果。
    • 7.读取网络结果。
    • 8.对数据进行缓存。
    • 9.返回网络读取的结果。

    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\. 创建缓存策略,强制缓存、对比缓存等
            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\. 根据策略,不使用网络,又没有缓存的直接报错,并返回错误码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\. 根据策略,不使用网络,有缓存的直接返回。
            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\. 前面两个都没有返回,继续执行下一个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\. 接收到网络结果,如果响应code式304,则使用缓存,返回缓存结果。
            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\. 读取网络结果。
            Response response = networkResponse.newBuilder()
                    .cacheResponse(stripBody(cacheResponse))
                    .networkResponse(stripBody(networkResponse))
                    .build();
            //8\. 对数据进行缓存。
            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\. 返回网络读取的结果。
                if (HttpMethod.invalidatesCache(networkRequest.method())) {
                    try {
                        cache.remove(networkRequest);
                    } catch (IOException ignored) {
                        // The cache cannot be written.
                    }
                }
            }
    
            return response;
        }
    }
    

    相关文章

      网友评论

          本文标题:okhttp之旅(六)--CacheInterceptor缓存拦

          本文链接:https://www.haomeiwen.com/subject/hdoksqtx.html