OkHttp解析三(拦截器)

拦截器

CacheInterceptor

缓存拦截器,在发出请求前,判断是否命中缓存。如果命中则可以不请求,直接使用缓存的响应。 (只会存在Get请求的缓存)

@Override
    public Response intercept(Chain chain) throws IOException {
        //todo 1.从缓存中获得对应请求的响应缓存
        Response cacheCandidate = cache != null
                ? cache.get(chain.request())
                : null;

        long now = System.currentTimeMillis();

        //todo 2.缓存策略,创建CacheStrategy ,创建时会判断是否能够使用缓存
        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.
        }

        //todo 3.没有网络请求也没有缓存
        //If we're forbidden from using the network and the cache is insufficient, fail.
        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();
        }

        //todo 4.没有请求,肯定就要使用缓存
        //If we don't need the network, we're done.
        if (networkRequest == null) {
            return cacheResponse.newBuilder()
                    .cacheResponse(stripBody(cacheResponse))
                    .build();
        }

        //todo 5.去发起请求
        Response networkResponse = null;
        try {
            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.
        //todo 6.有缓存,服务器返回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());
            }
        }

        //todo 7.没有缓存,走到这里说明缓存不可用 那就使用网络的响应
        Response response = networkResponse.newBuilder()
                .cacheResponse(stripBody(cacheResponse))
                .networkResponse(stripBody(networkResponse))
                .build();
        //todo 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);
            }

            if (HttpMethod.invalidatesCache(networkRequest.method())) {
                try {
                    cache.remove(networkRequest);
                } catch (IOException ignored) {
                    // The cache cannot be written.
                }
            }
        }

        return response;
    }

1.从缓存中获得对应请求的响应缓存

(通过url的md5数据 从文件缓存查找 (GET请求才有缓存))

 	public static String key(HttpUrl url) {
    	return ByteString.encodeUtf8(url.toString()).md5().hex();
  	}

  @Nullable Response get(Request request) {
    String key = key(request.url());
    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;
  }

  @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")) {
      // 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;
    }
  }

2.缓存策略

创建CacheStrategy ,创建时会判断是否能够使用缓存,在CacheStrategy 中存在两个成员:networkRequest与cacheResponse。

networkRequestcacheResponse说明
NullNot Null直接使用缓存
Not NullNull向服务器发起请求
NullNull直接gg,okhttp直接返回504
Not NullNot Null发起请求,若得到响应为304(无修改),则更新缓存响应并返回

请求头与响应头

响应头说明例子
Date消息发送的时间Date: Sat, 18 Nov 2028 06:17:41 GMT
Expires资源过期的时间Expires: Sat, 18 Nov 2028 06:17:41 GMT
Last-Modified资源最后修改时间Last-Modified: Fri, 22 Jul 2016 02:57:17 GMT
ETag资源在服务器的唯一标识ETag: “16df0-5383097a03d40”
Age服务器用缓存响应请求,该缓存从产生到现在经过多长时间(秒)Age: 3825683
Cache-Control--
响应头说明例子
If-Modified-Since服务器没有在指定的时间后修改请求对应资源,返回304(无修改)If-Modified-Since: Fri, 22 Jul 2016 02:57:17 GMT
If-None-Match服务器将其与请求对应资源的Etag值进行比较,匹配返回304If-None-Match: “16df0-5383097a03d40”
Cache-Control--
响应头例子说明
Cache-Control: no-cache忽略缓存
If-Modified-Since: 时间值一般为Data或lastModified,服务器没有在指定的时间后修改请求对应资源,返回304(无修改)
If-None-Match:标记值一般为Etag,将其与请求对应资源的Etag值进行比较;如果匹配,返回304

其中Cache-Control可以在请求头存在,也能在响应头存在,对应的value可以设置多种组合:

Cache-Control说明
1. max-age=[秒]资源最大有效时间,缓存的内容将在 xxx 秒后失效, 这个选项只在HTTP 1.1可用, 并如果和Last-Modified一起使用时, 优先级较高。
2. public所有内容都将被缓存(客户端和代理服务器都可缓存),比如客户端,代理服务器等都可以缓存资源。
3. private表明该资源只能被单个用户缓存,内容只缓存到私有缓存中(仅客户端可以缓存,代理服务器不可缓存)默认是private。
4. no-store资源不允许被缓存,所有内容都不会被缓存到缓存或 Internet 临时文件中。
5. no-cache(请求)不使用缓存,必须先与服务器确认返回的响应是否被更改,然后才能使用该响应来满足后续对同一个网址的请求。因此,如果存在合适的验证令牌 (ETag),no-cache 会发起往返通信来验证缓存的响应,如果资源未被更改,可以避免下载。
6. immutable(响应)资源不会改变。
7. min-fresh=[秒](请求)缓存最小新鲜度(用户认为这个缓存有效的时长)。
8. must-revalidate/proxy-revalidation:(响应)不允许使用过期缓存,如果缓存的内容失效,请求必须发送到服务器/代理以进行重新验证。
9. max-stale=[秒](请求)缓存过期后多久内仍然有效。

假设存在max-age=100,min-fresh=20。这代表了用户认为这个缓存的响应,从服务器创建响应 到 能够缓存使用的时间为100-20=80s。但是如果max-stale=100。这代表了缓存有效时间80s过后,仍然允许使用100s,可以看成缓存有效时长为180s。

Factory()

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);
                    }
                }
            }
        }

get()

这里是缓存策略get()的方法

 		/**
         * Returns a strategy to satisfy {@code request} using the a cached response {@code
         * response}.
         */
        public CacheStrategy get() {
            CacheStrategy candidate = getCandidate();
            //todo 如果可以使用缓存,那networkRequest必定为null;指定了只使用缓存但是networkRequest又不为null,冲突。那就gg(拦截器返回504)
            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;
        }

如果用户在创建请求时,配置了onlyIfCached这意味着用户这次希望这个请求只从缓存获得,不需要发起请求。那如果生成的CacheStrategy存在networkRequest这意味着肯定会发起请求,此时出现冲突!那会直接给到拦截器一个既没有networkRequest又没有cacheResponse的对象。拦截器直接返回用户504!

getCandidate()

获取缓存策略的判断方法

		 /**
         * Returns a strategy to use assuming the request can use the network.
         */
        private CacheStrategy getCandidate() {
            // No cached response.
            //todo 1、没有缓存,进行网络请求
            //cacheResponse是从缓存中找到的响应,如果为null,那就表示没有找到对应的缓存,创建的CacheStrategy实例对象只存在networkRequest,这代表了需要发起网络请求。
            if (cacheResponse == null) {
                return new CacheStrategy(request, null);
            }
            //继续往下走意味着cacheResponse必定存在,但是它不一定能用。后续进行有效性的一系列判断
            //todo 2、https请求,但是没有握手信息,进行网络请求
            //Drop the cached response if it's missing a required handshake.
            if (request.isHttps() && cacheResponse.handshake() == null) {
                return new CacheStrategy(request, null);
            }

            //todo 3、主要是通过响应码以及头部缓存控制字段判断响应能不能缓存,不能缓存那就进行网络请求
            //If this response shouldn't have been stored, it should never be used
            //as a response source. This check should be redundant as long as the
            //persistence store is well-behaved and the rules are constant.
            if (!isCacheable(cacheResponse, request)) {
                return new CacheStrategy(request, null);
            }
			//todo 4、用户的请求配置
            CacheControl requestCaching = request.cacheControl();
            //如果 请求包含:CacheControl:no-cache 忽略缓存,需要与服务器验证缓存有效性
            // 或者请求头包含 If-Modified-Since:时间 值为lastModified或者data 如果服务器没有在该头部指定的时间之后修改了请求的数据,服务器返回304(无修改)
            // 或者请求头包含 If-None-Match:值就是Etag(资源标记)服务器将其与存在服务端的Etag值进行比较;如果匹配,返回304
            // 请求头中只要存在三者中任意一个,进行网络请求
            if (requestCaching.noCache() || hasConditions(request)) {
                return new CacheStrategy(request, null);
            }

            //todo 5、资源是否不变
            //如果缓存响应中存在 Cache-Control:immutable 响应内容将一直不会改变,可以使用缓存
            CacheControl responseCaching = cacheResponse.cacheControl();
            if (responseCaching.immutable()) {
                return new CacheStrategy(null, cacheResponse);
            }

            //todo 6、响应的缓存有效期
            //根据 缓存响应的 控制缓存的响应头 判断是否允许使用缓存
            //缓存存活时间 < 缓存新鲜度 - 缓存最小新鲜度 + 过期后继续使用时长
            // 6.1、获得缓存的响应从创建到现在的时间
            long ageMillis = cacheResponseAge();
            //todo
            // 6.2、获取这个响应有效缓存的时长
            long freshMillis = computeFreshnessLifetime();
            if (requestCaching.maxAgeSeconds() != -1) {
                //todo 如果请求中指定了 max-age 表示指定了能拿的缓存有效时长,就需要综合响应有效缓存时长与请求能拿缓存的时长,获得最小的能够使用响应缓存的时长
                freshMillis = Math.min(freshMillis,
                        SECONDS.toMillis(requestCaching.maxAgeSeconds()));
            }
            //todo
            // 6.3 请求包含  Cache-Control:min-fresh=[秒]  能够使用还未过指定时间的缓存 (请求认为的缓存有效时间)
            long minFreshMillis = 0;
            if (requestCaching.minFreshSeconds() != -1) {
                minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
            }

            //todo
            // 6.4
            //  6.4.1、Cache-Control:must-revalidate 可缓存但必须再向源服务器进行确认
            //  6.4.2、Cache-Control:max-stale=[秒] 缓存过期后还能使用指定的时长  如果未指定多少秒,则表示无论过期多长时间都可以;如果指定了,则只要是指定时间内就能使用缓存
            // 前者会忽略后者,所以判断了不必须向服务器确认,再获得请求头中的max-stale
            long maxStaleMillis = 0;
            if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
                maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
            }

            //todo
            // 6.5 不需要与服务器验证有效性 && 响应存在的时间+请求认为的缓存有效时间 小于 缓存有效时长+过期后还可以使用的时间
            // 允许使用缓存
            if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
                Response.Builder builder = cacheResponse.newBuilder();
                //todo 如果已过期,但未超过 过期后继续使用时长,那还可以继续使用,只用添加相应的头部字段
                if (ageMillis + minFreshMillis >= freshMillis) {
                    builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
                }
                //todo 如果缓存已超过一天并且响应中没有设置过期时间也需要添加警告
                long oneDayMillis = 24 * 60 * 60 * 1000L;
                if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
                    builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
                }
                return new CacheStrategy(null, builder.build());
            }
            //总体来说,只要不忽略缓存并且缓存未过期,则使用缓存。

            // Find a condition to add to the request. If the condition is satisfied, the
            // response body
            // will not be transmitted.
            //todo 7、缓存过期了
            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.
            }
            //todo 如果设置了 If-None-Match/If-Modified-Since 服务器是可能返回304(无修改)的,使用缓存的响应体
            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);
        }

1、没有缓存,进行网络请求

	// No cached response.
	if (cacheResponse == null) {
	    return new CacheStrategy(request, null);
	}

2、https请求

意味着cacheResponse必定存在,但是它不一定能用。后续进行有效性的一系列判断

 	//Drop the cached response if it's missing a required handshake.
	if (request.isHttps() && cacheResponse.handshake() == null) {
	 	return new CacheStrategy(request, null);
	}

如果本次请求是HTTPS,但是缓存中没有对应的握手信息,那么缓存无效。

3、响应码以及响应头

		//If this response shouldn't have been stored, it should never be used
        //as a response source. This check should be redundant as long as the
        //persistence store is well-behaved and the rules are constant.
        if (!isCacheable(cacheResponse, request)) {
             return new CacheStrategy(request, null);
        }
public static boolean isCacheable(Response response, Request request) {
        // Always go to network for uncacheable response codes (RFC 7231 section 6.1),
        // This implementation doesn't support caching partial content.
        switch (response.code()) {
            //todo 对于 200, 203, 204, 300, 301, 404, 405, 410, 414, 501, 308 只判断是不是存在cache-control:nostore (资源不能被缓存), 所以如果服务器给到了这个响应头,那就和前面两个判定一致(缓存不可用)。否则继续进一步判断缓存是否可用
            // 302, 307 (重定向)则需要进一步判断是不是存在一些允许缓存的响应头。需要存在: Expires或者CacheControl:max-age/public/private 才判断是不是存在。同时不存在cache-control:nostore,那就可以继续进一步判断缓存是否可用。
            case HTTP_OK:
            case HTTP_NOT_AUTHORITATIVE:
            case HTTP_NO_CONTENT:
            case HTTP_MULT_CHOICE:
            case HTTP_MOVED_PERM:
            case HTTP_NOT_FOUND:
            case HTTP_BAD_METHOD:
            case HTTP_GONE:
            case HTTP_REQ_TOO_LONG:
            case HTTP_NOT_IMPLEMENTED:
            case StatusLine.HTTP_PERM_REDIRECT:
                // These codes can be cached unless headers forbid it.
                break;

            case HTTP_MOVED_TEMP:
            case StatusLine.HTTP_TEMP_REDIRECT:
                // These codes can only be cached with the right response headers.
                // http://tools.ietf.org/html/rfc7234#section-3
                // s-maxage is not checked because OkHttp is a private cache that should ignore
                // s-maxage.
                if (response.header("Expires") != null
                        || response.cacheControl().maxAgeSeconds() != -1
                        || response.cacheControl().isPublic()
                        || response.cacheControl().isPrivate()) {
                    break;
                }
                // Fall-through.

            default:
                // All other codes cannot be cached.
                return false;
        }

        // A 'no-store' directive on request or response prevents the response from being cached.
        return !response.cacheControl().noStore() && !request.cacheControl().noStore();
    }

1、响应码不为 200, 203, 204, 300, 301, 404, 405, 410, 414, 501, 308,302,307 缓存不可用;
2、当响应码为302或者307时,未包含某些响应头,则缓存不可用;
3、当存在Cache-Control: no-store响应头则缓存不可用。

4、用户的请求配置

	CacheControl requestCaching = request.cacheControl();
	if (requestCaching.noCache() || hasConditions(request)) {
	    return new CacheStrategy(request, null);
	}
	private static boolean hasConditions(Request request) {
	    return request.header("If-Modified-Since") != null || request.header("If-None-Match") != null;
	}

OkHttp需要先对用户本次发起的Request进行判定,如果用户指定了Cache-Control: no-cache(不使用缓存)的请求头或者请求头包含 If-Modified-Since或If-None-Match(请求验证),那么就不允许使用缓存。
这意味着如果用户请求头中包含了这些内容,那就必须向服务器发起请求。但是需要注意的是,OkHttp并不会缓存304的响应,如果是此种情况,即用户主动要求与服务器发起请求,服务器返回的304(无响应体),则直接把304的响应返回给用户:“既然你主动要求,我就只告知你本次请求结果”。而如果不包含这些请求头,那继续判定缓存有效性。

5、资源是否不变

	 CacheControl responseCaching = cacheResponse.cacheControl();
            if (responseCaching.immutable()) {
                return new CacheStrategy(null, cacheResponse);
            }

如果缓存的响应中包含Cache-Control: immutable,这意味着对应请求的响应内容将一直不会改变。此时就可以直接使用缓存。否则继续判断缓存是否可用

6、响应的缓存有效期

根据缓存响应中的一些信息判定缓存是否处于有效期内。
缓存存活时间 < 缓存新鲜度 - 缓存最小新鲜度 + 过期后继续使用时长
新鲜度 理解为有效时间
缓存新鲜度-缓存最小新鲜度 就代表了缓存真正有效的时间。

6.1缓存到现在存活的时间
		long ageMillis = cacheResponseAge();

		/**
         * Returns the current age of the response, in milliseconds. The calculation is specified
         * by RFC
         * 7234, 4.2.3 Calculating Age.
         */
        private long cacheResponseAge() {
            //todo
            // 响应Data字段:服务器发出这个消息的时间
            // 响应Age字段: 当代理服务器用自己缓存的实体去响应请求时,会用该头部表明该实体从产生到现在经过多长时间了
            // 计算收到响应的时间与服务器创建发出这个消息的时间差值:apparentReceivedAge
            // 取出apparentReceivedAge 与ageSeconds最大值并赋予receivedAge (代理服务器缓存的时间,意义如上的结果,但是要拿最大值)
            // 计算从发起请求到收到响应的时间差responseDuration
            // 计算现在与收到响应的时间差residentDuration
            // 三者加起来就是响应已存在的总时长
            long apparentReceivedAge = servedDate != null
                    ? Math.max(0, receivedResponseMillis - servedDate.getTime())
                    : 0;
            long receivedAge = ageSeconds != -1
                    ? Math.max(apparentReceivedAge, SECONDS.toMillis(ageSeconds))
                    : apparentReceivedAge;
            long responseDuration = receivedResponseMillis - sentRequestMillis;
            long residentDuration = nowMillis - receivedResponseMillis;
            return receivedAge + responseDuration + residentDuration;
        }
步骤属性名含义
1apparentReceivedAge客户端收到响应到服务器发出响应的一个时间差
1seredData从缓存中获得的Data响应头对应的时间(服务器发出本响应的时间); receivedResponseMillis为本次响应对应的客户端发出请求的时间
2receivedAge客户端的缓存,在收到时就已经存在多久了
2ageSeconds从缓存中获得的Age响应头对应的秒数 (本地缓存的响应是由服务器的缓存返回,这个缓存在服务器存在的时间)
2ageSeconds与上一步计算结果apparentReceivedAge的最大值为收到响应时,这个响应数据已经存在多久。

假设我们发出请求时,服务器存在一个缓存,其中 Data: 0点。 此时,客户端在1小时候发起请求,此时由服务器在缓存中插入Age: 1小时并返回给客户端,此时客户端计算的receivedAge就是1小时,这就代表了客户端的缓存在收到时就已经存在多久了。(不代表到本次请求时存在多久了)

步骤属性名含义
3responseDuration是缓存对应的请求,在发送请求与接收请求之间的时间差
4residentDuration是这个缓存接收到的时间到现在的一个时间差
5receivedAge + responseDuration + residentDuration缓存在客户端收到时就已经存在的时间 + 请求过程中花费的时间 + 本次请求距离缓存获得的时间,就是缓存真正存在了多久。
6.2、缓存新鲜度(有效时间)
			long freshMillis = computeFreshnessLifetime();
            if (requestCaching.maxAgeSeconds() != -1) {
                freshMillis = Math.min(freshMillis,
                        SECONDS.toMillis(requestCaching.maxAgeSeconds()));
            }

		/**
         * Returns the number of milliseconds that the response was fresh for, starting from the
         * served
         * date.
         */
        private long computeFreshnessLifetime() {
            CacheControl responseCaching = cacheResponse.cacheControl();
            /**
             * todo
             *  max-age:资源最大有效时间/秒
             *  expires:缓存过期的时间(服务器时间,可能客户端时间和服务器不一致)
             *    服务器如果发出了Data(服务器发出这个消息的时间) 则expires-data为有效时间
             *    没发出Data 则用 expires-收到响应的时间  为有效时间
             *  Last-Modified: 请求的数据最后修改的时间  进行试探性过期时间的计算
             *    服务器如果发出了Data(服务器发出这个消息的时间) 则data-lastModified 作为有效时间
             *    没发出Data 则用 对应缓存响应发起请求的时间-lastModified  作为有效时间
             */
            if (responseCaching.maxAgeSeconds() != -1) {
                return SECONDS.toMillis(responseCaching.maxAgeSeconds());
            } else if (expires != null) {
                long servedMillis = servedDate != null
                        ? servedDate.getTime()
                        : receivedResponseMillis;
                long delta = expires.getTime() - servedMillis;
                return delta > 0 ? delta : 0;
            } else if (lastModified != null
                    && cacheResponse.request().url().query() == null) {
                // As recommended by the HTTP RFC and implemented in Firefox, the
                // max age of a document should be defaulted to 10% of the
                // document's age at the time it was served. Default expiration
                // dates aren't used for URIs containing a query.
                long servedMillis = servedDate != null
                        ? servedDate.getTime()
                        : sentRequestMillis;
                long delta = servedMillis - lastModified.getTime();
                return delta > 0 ? (delta / 10) : 0;
            }
            return 0;
        }

缓存新鲜度(有效时长)的判定会有几种情况,按优先级排列如下:
1、缓存响应包含Cache-Control: max-age=[秒]资源最大有效时间
2、缓存响应包含Expires: 时间,则通过Data或接收该响应时间计算资源有效时间
3、缓存响应包含Last-Modified: 时间,则通过Data或发送该响应对应请求的时间计算资源有效时间;并且根据建议以及在Firefox浏览器的实现,使用得到结果的10%来作为资源的有效时间。

6.3、缓存最小新鲜度
			long minFreshMillis = 0;
            if (requestCaching.minFreshSeconds() != -1) {
                minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
            }

如果用户的请求头中包含Cache-Control: min-fresh=[秒],代表用户认为这个缓存有效的时长。假设本身缓存新鲜度为: 100毫秒,而缓存最小新鲜度为:10毫秒,那么缓存真正有效时间为90毫秒。

6.4、缓存过期后仍有效时长
			long maxStaleMillis = 0;
            if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
                maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
            }

这个判断中第一个条件为缓存的响应中没有包含Cache-Control: must-revalidate(不可用过期资源),获得用户请求头中包含Cache-Control: max-stale=[秒]缓存过期后仍有效的时长。

6.5、判定缓存是否有效
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
                Response.Builder builder = cacheResponse.newBuilder();
                if (ageMillis + minFreshMillis >= freshMillis) {
                    builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
                }
                long oneDayMillis = 24 * 60 * 60 * 1000L;
                if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
                    builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
                }
                return new CacheStrategy(null, builder.build());
            }

缓存存活时间+缓存最小新鲜度 < 缓存新鲜度+过期后继续使用时长,代表可以使用缓存。
假设 缓存到现在存活了:100 毫秒; 用户认为缓存有效时间(缓存最小新鲜度)为:10 毫秒; 缓存新鲜度为: 100 毫秒; 缓存过期后仍能使用: 0 毫秒; 这些条件下,首先缓存的真实有效时间为: 90毫秒,而缓存已经过了这个时间,所以无法使用缓存。
不等式可以转换为: 缓存存活时间 < 缓存新鲜度 - 缓存最小新鲜度 + 过期后继续使用时长,即 存活时间 < 缓存有效时间 + 过期后继续使用时间

总体来说,只要不忽略缓存并且缓存未过期,则使用缓存。

7、缓存过期处理

			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.
            }

表示缓存已经过期无法使用。此时我们判定缓存的响应中如果存在Etag,则使用If-None-Match交给服务器进行验证;如果存在Last-Modified或者Data,则使用If-Modified-Since交给服务器验证。服务器如果无修改则会返回304,这时候注意
由于是缓存过期而发起的请求(与第4个判断用户的主动设置不同),如果服务器返回304,那框架会自动更新缓存,所以此时CacheStrategy既包含networkRequest也包含cacheResponse

3.没有网络请求也没有缓存

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();

4.没有请求,肯定就要使用缓存

 return cacheResponse.newBuilder()
                    .cacheResponse(stripBody(cacheResponse))
                    .build();

5.去发起请求

Response networkResponse = null;
        try {
            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());
            }
        }

6.有缓存

服务器返回304无修改,那就使用缓存的响应修改了时间等数据后作为本次请求的响应

 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;

7.没有缓存

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

8.进行缓存

if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response,
                    networkRequest)) {
                // Offer this request to the cache.
                CacheRequest cacheRequest = cache.put(response);
                return cacheWritingResponse(cacheRequest, response);
            }

9.总结

1、如果从缓存获取的Response是null,那就需要使用网络请求获取响应;
2、如果是Https请求,但是又丢失了握手信息,那也不能使用缓存,需要进行网络请求;
3、如果判断响应码不能缓存且响应头有no-store标识,那就需要进行网络请求;
4、如果请求头有no-cache标识或者有If-Modified-Since/If-None-Match,那么需要进行网络请求;
5、如果响应头没有no-cache标识,且缓存时间没有超过极限时间,那么可以使用缓存,不需要进行网络请求;
6、如果缓存过期了,判断响应头是否设置Etag/Last-Modified/Date,没有那就直接使用网络请求否则需要考虑服务器返回304;
7、只要需要进行网络请求,请求头中就不能包含only-if-cached,否则框架直接返回504!
8、缓存拦截器本身主要逻辑其实都在缓存策略中,拦截器本身逻辑非常简单,如果确定需要发起网络请求,则下一个拦截器为ConnectInterceptor

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值