上来就怼,接着上篇BridgeInterceptor的桥接器我们今天来看下下级拦截器CacheInterceptor。
CacheInterceptor从字面意思理解为缓存的拦截器,其实它实际的功能也正是如此,来看下其intercept的源码。
@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.
// 如果我们的网络被禁用了并且缓存不完整/异常。重新构建Respose并把其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 we don't need the network, we're done.
// 不需要网络请求时,body置空
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
Response networkResponse = null;
try {
networkResponse = chain.proceed(networkRequest); // 执行proceed方法即链的下一个interceptor
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
// 放生io异常时,释放资源避免泄漏
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
// If we have a cache response too, then we're doing a conditional get.
// 当我们有一个缓存存在时,也是根据设定好的条件判断进行操作
if (cacheResponse != null) {
if (networkResponse.code() == HTTP_NOT_MODIFIED) { // 服务器数据没变化时(304)
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());
}
}
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;
}
从上面可以看出其实可以拆分出两步:1、拿到及使用原来的缓存;2、进行这一次的缓存。
拿到及使用原来的缓存
关键代码
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
其中构建类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)) { // //响应对象在代理缓存中存在的时间(s)
etag = value;
} else if ("Age".equalsIgnoreCase(fieldName)) { // 同上
ageSeconds = HttpHeaders.parseSeconds(value, -1);
}
}
}
}
get方法如下
/**
* Returns a strategy to satisfy {@code request} using the a cached response {@code response}.
*/
public CacheStrategy get() {
CacheStrategy candidate = getCandidate();
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;
}
方法很简单,核心在于getCandidate,好,我们接着看下这个方法
/** Returns a strategy to use assuming the request can use the network. */
private CacheStrategy getCandidate() {
// No cached response.
// 没有缓存时
if (cacheResponse == null) {
return new CacheStrategy(request, null);
}
// Drop the cached response if it's missing a required handshake.
// https缓存,但是没有经过握手过程时
if (request.isHttps() && cacheResponse.handshake() == null) {
return new CacheStrategy(request, null);
}
// 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);
}
// 获取requst的缓存控制器
CacheControl requestCaching = request.cacheControl();
// 没有缓存、requst被标记为不能缓存
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
long ageMillis = cacheResponseAge();
long freshMillis = computeFreshnessLifetime();
if (requestCaching.maxAgeSeconds() != -1) {
freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
}
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
long maxStaleMillis = 0;
// 获取Response缓存控制器
CacheControl responseCaching = cacheResponse.cacheControl();
// 获得过期时间
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
// 通过过期时间比较判断是否设置Respose的相应header值
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());
}
// Find a condition to add to the request. If the condition is satisfied, the response body
// will not be transmitted.
// 查看其中是否有合适的条件,有的话respose被置空
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.
}
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);
}
到这我们先了解下header中关于缓存的相关字段
Expires
Expires: Thu, 12 Jan 2017 11:01:33 GMT
表示到期时间,一般用在response报文中,当超过此时间响应将被认为是无效的而需要网络连接,反之直接使用缓存条件GET
客户端发送条件get请求,如果缓存是有效的,则返回304 Not Modifiled,否则才返回body。ETag
ETag是对资源文件的一种摘要,当客户端第一次请求某个对象,服务器在响应头返回
ETag: “5694c7ef-24dc”
客户端再次请求时,通过发送
If-None-Match:”5694c7ef-24dc”
交给服务器进行判断,如果仍然可以缓存使用,服务器就直接返回304 Not ModifiledVary
Vary: *
告诉客户端和缓存服务器不要缓存任何信息
Vary: header-name, header-name, …
逗号分隔的一系列http头部名称,用于确定缓存是否可用
作用:动态服务,防止客户端误使用了用于pc端的缓存。即使请求的是相同资源,因Vary指定的首部字段不同,也必须从源服务器请求Cache Control
客户端可以在HTTP**请求**中使用的标准 Cache-Control 指令
Cache-Control: max-age=
Cache-Control: max-stale[=]
Cache-Control: min-fresh=
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: only-if-cached
服务器可以在响应中使用的标准 Cache-Control 指令。
Cache-control: must-revalidate
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: public
Cache-control: private
Cache-control: proxy-revalidate
Cache-Control: max-age=
Cache-control: s-maxage=
1) 可缓存性
public
表明其他用户也可以利用缓存。
private
表明缓存只对单个用户有效,不能作为共享缓存。
no-cache
强制所有缓存了该响应的缓存用户,在使用已存储的缓存数据前,发送带验证的请求到原始服务器
no-store
缓存不应存储有关客户端请求或服务器响应的任何内容。
only-if-cached
表明客户端只接受已缓存的响应,并且不要向原始服务器检查是否有更新的拷贝(相当于禁止使用网络连接)
2) 到期
max-age=<seconds>
设置缓存存储的最大周期,超过这个时间缓存被认为过期(单位秒)。与Expires相反,时间是相对于请求的时间。
s-maxage=<seconds>
覆盖max-age 或者 Expires 头,但是仅适用于共享缓存(比如各个代理),并且私有缓存中它被忽略。
max-stale[=<seconds>]
表明客户端愿意接收一个已经过期的资源,且可选地指定响应不能超过的过时时间。
min-fresh=<seconds>
表示客户端希望在指定的时间内获取最新的响应。
3) 有效性
must-revalidate
缓存必须在使用之前验证旧资源的状态,并且不可使用过期资源。
proxy-revalidate
与must-revalidate作用相同,但它仅适用于共享缓存(例如代理),并被私有缓存忽略。
immutable
表示响应正文不会随时间而改变。资源(如果未过期)在服务器上不发生改变,因此客户端不应发送重新验证请求头(例如If-None-Match或If-Modified-Since)来检查更新,即使用户显式地刷新页面。
我们通过在interceptor中拿到缓存CacheStrategy.Factory(now, chain.request().get()-->getCandidate() 后判断是否要使用缓存/网络请求->对应如下:
如果进行网络请求,在得到结果后更新缓存。其中缓存这里是通过Cache的内部类InternalCache通过控制DiskLruCache来进行增删改查(懒得自己画,盗图一张,哈哈):