源码分析基于 3.14.4
关键字:拦截器CacheInterceptor
https://www.jianshu.com/p/60aaee13ff65上一篇,讲了CallServerInterceptor拦截器的作用。
这次分析CacheInterceptor
缓存拦截,顾名思义就是做缓存处理的。
还是看CacheInterceptor.intercept
(1)说实在话,缓存的逻辑比较复杂,我也不是每个细节都看懂了,只知道个大概;
(2)cache.get(chain.request()),根据url的MD5值获取缓存cacheCandidate ,candidate是候选的意思,表示可能会返回这个;
(3)new CacheStrategy.Factory,根据Request、Response 、当前时间创建缓存策略CacheStrategy ,这里面是对能否使用缓存做逻辑处理,后面会重点分析;
(4)networkRequest 表示请求实体,cacheResponse 表示缓存实体,两者共同决定使用请求还是缓存;
(5)无请求且无缓存,则networkRequest == null && cacheResponse == null成立,构建504Response返回,通常发生在客户端只希望使用缓存,请求头带only-if-cached的情况;
(6)无请求,则networkRequest == null条件成立,直接返回缓存;
(7)添加(6)不成立,即有请求,则调用后续拦截器发起请求;
(8)后续拦截器返回,即服务器返回结果,有缓存且服务器返回304(表示内容没有变化,可以用缓存),则networkResponse.code() == HTTP_NOT_MODIFIED条件成立,更新缓存的发起请求时间、接收响应时间、缓存响应、网络响应,最后返回;
(9)不是返回304,响应有body且可以缓存,例如返回200且请求头不带no-store且响应头不带no-store,则HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)条件成立,把响应缓存起来并返回;
(10)如果请求是POST、DELETED的,删除缓存;
(11)条件(9)不成立,则直接返回响应;
@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 (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();
}
......
networkResponse = chain.proceed(networkRequest);
......
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;
}
......
}
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())) {
cache.remove(networkRequest);
......
}
}
return response;
}
流程1.png
看下构建缓存策略是如何处理networkRequest 以及cacheResponse的,主要看CacheStrategy.Factory构造方法以及get方法;
先看CacheStrategy.Factory构造方法,
主要是构建缓存策略构造,获取缓存发起时间(即发起请求时间)、缓存接收数据、读取跟缓存相关的请求头(Date、Expires、Last-Modified等);
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);
}
}
}
}
CacheStrategy.Factory.get
(1)getCandidate(),获取候选缓存策略;
(2)如果networkRequest 不为空且请求头包含only-if-cached,则把构建一个networkRequest以及cacheResponse为空的缓存策略;
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;
}
CacheStrategy.Factory.getCandidate
(1)这个方法有点长,主要是获取各种时间计算;
(2)如果是HTTPS请求但是握手信息为空,则request.isHttps() && cacheResponse.handshake()条件成立,返回cacheResponse为空的缓存策略;
(3)如果缓存不应该被缓存的,则!isCacheable(cacheResponse, request)条件成立,同样返回cacheResponse为空的缓存策略,例如cacheResponse返回码不是200、获取请求头带no-store、或者cacheResponse头带no-store;
(4)如果请求不使用缓存、或者需要询问服务器是否可以使用缓存,则返回cacheResponse为空的缓存策略,例如请求头带no-cache、If-Modified-Since、If-None-Match;
(5)cacheResponseAge,计算缓存年龄;
(6)computeFreshnessLifetime,计算缓存新鲜度;
(7)如果缓存没有过有效期,则ageMillis + minFreshMillis < freshMillis + maxStaleMillis条件成立,返回networkRequest 为空而cacheResponse不为空的缓存策略,表示直接使用缓存;
(8)如果缓存头包含ETag、Last-Modified、Date其中一个请求头,则返回networkRequest 不为空而cacheResponse为空缓存策略,表示需要请求服务器;
(9)条件(8)不成立,则返回networkRequest 且cacheResponse不为空的缓存策略,表示需要跟服务器协商,这个缓存能不能使用;
private CacheStrategy getCandidate() {
......
if (request.isHttps() && cacheResponse.handshake() == null) {
return new CacheStrategy(request, null);
}
if (!isCacheable(cacheResponse, request)) {
return new CacheStrategy(request, null);
}
CacheControl requestCaching = request.cacheControl();
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
CacheControl responseCaching = cacheResponse.cacheControl();
......
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
......
return new CacheStrategy(null, builder.build());
}
......
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);
}
总结
(1)CacheInterceptor缓存拦截,顾名思义就是做缓存处理的;
(2)OkHttp默认支持缓存,配置OkHttpClient.cahe就可以开启缓存,只要服务器做相应处理;
(3)只缓存GET请求;
(4)缓存策略中的networkRequest 以及cacheResponse决定是否使用缓存;
networkRequest 、cacheResponse两者为空,表示客户端只希望使用缓存only-if-cached,返回504响应;
networkRequest 为空,cacheResponse不为空,则返回缓存;
networkRequest 不为空,cacheResponse为空,则没有缓存可以使用,需要请求服务器;
networkRequest 、cacheResponse两者都不为空,则需要跟服务器协商,过去缓存能不能使用。
以上分析有不对的地方,请指出,互相学习,谢谢哦!
网友评论