| CacheInterceptor拦截器在说第三个拦截器缓存拦截器之前,我们先了解下http协议的缓存机制是怎么样的 缓存规则分为强制缓存和对比缓存两种。 http把对于缓存的控制规则都放在头部的几个字段里了。 Cache-Control Cache-Control常见的取值有private、public、no-cache、max-age,no-store,默认为private private: 客户端可以缓存public: 客户端和代理服务器都可缓存
 max-age: 内容将在 xxx 秒后失效,单位秒
 no-cache: 使用对比缓存来验证缓存数据,会发送请求和服务器对比,看是否使用本地缓存的
 no-store: 所有内容都不会缓存,强制缓存,对比缓存都不会触发
 强制缓存 假如配置了max-age的值为3600,那么当前请求就会默认缓存1个小时,在一个小时内,去请求这条数据,都会使用本地的缓存数据作为响应。 假如no-store,则每次请求都会去服务器请求最新的数据 对比缓存 如果使用对比缓存,那么服务器会去对比客户端发送过来的数据和服务器上的资源是不是一样的,如果一样,则服务器只会响应一个302状态,并不会把客户端请求的资源响应回去,当客户端接收到响应,解析为302,则会去缓存中获取数据。否则解析获取最新响应数据。 对比缓存又有2组规则:ETag/If-None-Match、Last-Modified/If-Modified-Since ETag/If-None-Match 当第一次请求资源时,服务器会在响应头里加上ETag标识,如W/“4342c344-8d3”,该标识的生成规则由服务器决定,一般是 文件的hash值。 当再次请求资源时,客户端的头会附带If-None-Match,值为W/“4342c344-8d3”,服务器接收到请求后,如果和服务器上的资源运算出的ETag相同,那它就会返回302,否则就会返回200并附带资源文件到响应里。 Last-Modified/If-Modified-Since 当第一次请求资源时,服务器响应头里会有资源的最后修改时间Last-Modified:Fri, 21 Jan 2022 02:54:57 GMT。 下一次请求,客户端就会在请求头上增加头If-Modified-Since:Fri, 21 Jan 2022 02:54:57 GMT。服务器收到请求后,如果这个时间比服务器该资源最后的修改时间早的话,说明被改动过,返回最新资源,否则服务器返回302,客户端则取缓存资源。 注意上面的两组规则,ETag/If-None-Match 优先级大于 Last-Modified/If-Modified-Since 知道以上缓存规则后,我们再来解读CacheInterceptor这个拦截器的代码: 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()); 
    }
    
    
    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();
    }
    Response networkResponse = null;
    try {
        
        networkResponse = chain.proceed(networkRequest);
    } finally {
        
        if (networkResponse == null && cacheCandidate != null) {
            closeQuietly(cacheCandidate.body());
        }
    }
    
    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;
        } 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)) {
            CacheRequest cacheRequest = cache.put(response);
            
            return cacheWritingResponse(cacheRequest, response);
        }
		
        if (HttpMethod.invalidatesCache(networkRequest.method())) {
            try {
                cache.remove(networkRequest);
            } catch (IOException ignored) {
                
            }
        }
    }
    return response;
}
 |