源碼分析基于 3.14.4
關(guān)鍵字:攔截器CacheInterceptor
http://www.reibang.com/p/60aaee13ff65上一篇,講了CallServerInterceptor攔截器的作用菜谣。
這次分析CacheInterceptor
緩存攔截,顧名思義就是做緩存處理的归榕。
還是看CacheInterceptor.intercept
(1)說實(shí)在話全闷,緩存的邏輯比較復(fù)雜漂问,我也不是每個細(xì)節(jié)都看懂了,只知道個大概震糖;
(2)cache.get(chain.request())录肯,根據(jù)url的MD5值獲取緩存cacheCandidate ,candidate是候選的意思吊说,表示可能會返回這個论咏;
(3)new CacheStrategy.Factory,根據(jù)Request颁井、Response 厅贪、當(dāng)前時間創(chuàng)建緩存策略CacheStrategy ,這里面是對能否使用緩存做邏輯處理雅宾,后面會重點(diǎn)分析养涮;
(4)networkRequest 表示請求實(shí)體,cacheResponse 表示緩存實(shí)體眉抬,兩者共同決定使用請求還是緩存贯吓;
(5)無請求且無緩存,則networkRequest == null && cacheResponse == null成立蜀变,構(gòu)建504Response返回悄谐,通常發(fā)生在客戶端只希望使用緩存,請求頭帶only-if-cached的情況;
(6)無請求库北,則networkRequest == null條件成立爬舰,直接返回緩存;
(7)添加(6)不成立贤惯,即有請求洼专,則調(diào)用后續(xù)攔截器發(fā)起請求;
(8)后續(xù)攔截器返回孵构,即服務(wù)器返回結(jié)果屁商,有緩存且服務(wù)器返回304(表示內(nèi)容沒有變化,可以用緩存)颈墅,則networkResponse.code() == HTTP_NOT_MODIFIED條件成立蜡镶,更新緩存的發(fā)起請求時間、接收響應(yīng)時間恤筛、緩存響應(yīng)官还、網(wǎng)絡(luò)響應(yīng),最后返回毒坛;
(9)不是返回304望伦,響應(yīng)有body且可以緩存林说,例如返回200且請求頭不帶no-store且響應(yīng)頭不帶no-store,則HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)條件成立屯伞,把響應(yīng)緩存起來并返回腿箩;
(10)如果請求是POST、DELETED的劣摇,刪除緩存珠移;
(11)條件(9)不成立,則直接返回響應(yīng)末融;
@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;
}
看下構(gòu)建緩存策略是如何處理networkRequest 以及cacheResponse的钧惧,主要看CacheStrategy.Factory構(gòu)造方法以及get方法;
先看CacheStrategy.Factory構(gòu)造方法勾习,
主要是構(gòu)建緩存策略構(gòu)造浓瞪,獲取緩存發(fā)起時間(即發(fā)起請求時間)、緩存接收數(shù)據(jù)语卤、讀取跟緩存相關(guān)的請求頭(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眼滤,則把構(gòu)建一個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)這個方法有點(diǎn)長,主要是獲取各種時間計算诅需;
(2)如果是HTTPS請求但是握手信息為空漾唉,則request.isHttps() && cacheResponse.handshake()條件成立,返回cacheResponse為空的緩存策略堰塌;
(3)如果緩存不應(yīng)該被緩存的赵刑,則!isCacheable(cacheResponse, request)條件成立,同樣返回cacheResponse為空的緩存策略场刑,例如cacheResponse返回碼不是200般此、獲取請求頭帶no-store、或者cacheResponse頭帶no-store牵现;
(4)如果請求不使用緩存铐懊、或者需要詢問服務(wù)器是否可以使用緩存,則返回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為空緩存策略机打,表示需要請求服務(wù)器矫户;
(9)條件(8)不成立,則返回networkRequest 且cacheResponse不為空的緩存策略残邀,表示需要跟服務(wù)器協(xié)商皆辽,這個緩存能不能使用;
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);
}
總結(jié)
(1)CacheInterceptor緩存攔截芥挣,顧名思義就是做緩存處理的;
(2)OkHttp默認(rèn)支持緩存驱闷,配置OkHttpClient.cahe就可以開啟緩存,只要服務(wù)器做相應(yīng)處理空免;
(3)只緩存GET請求空另;
(4)緩存策略中的networkRequest 以及cacheResponse決定是否使用緩存;
networkRequest 蹋砚、cacheResponse兩者為空扼菠,表示客戶端只希望使用緩存only-if-cached,返回504響應(yīng)坝咐;
networkRequest 為空循榆,cacheResponse不為空,則返回緩存墨坚;
networkRequest 不為空秧饮,cacheResponse為空,則沒有緩存可以使用框杜,需要請求服務(wù)器浦楣;
networkRequest 瘩将、cacheResponse兩者都不為空弛槐,則需要跟服務(wù)器協(xié)商,過去緩存能不能使用苇侵。
以上分析有不對的地方油狂,請指出历恐,互相學(xué)習(xí)寸癌,謝謝哦!