OKhttp 缓存策略
缓存的意义:
在网络请求的过程中,都要使用到缓存,缓存的意义在于,对于客户端来说,使用缓存数据能够缩短页面展示数据的时间,优化用户体验,同时降低请求网络数据的频率,避免流量浪费。对于服务端来说,使用缓存能够分解一部分服务端的压力。
在介绍OkHttp框架的缓存模块之前,先介绍一下http缓存相关的基础知识:
网络缓存类型根据缓存策略的不同主要可以分为两种类型:强制缓存与对比缓存,如下图所示
所谓强制缓存是指,请求网络数据时,如果本地存在缓存数据且缓存数据有效,则直接使用缓存数据。
对比缓存:
请求网络数据时,如果本地存在缓存数据且没有过期,先要发给服务端进行校验,来决定缓存数据是否需要更新,如果需要更新则网络端会返回新的数据,如果不需要更近则直接使用缓存数据。
在http协议中具体参数是通过head中的Last-Modified/If-Modified-Since来实现的,服务端返回Last-Modified参数,标记出资源最后修改的时间,客户端询问缓存是否过期的时候将此时间数据放入If-Modified-Since参数中,如果缓存数据可用则返回304状态码,否则直接返回接口数据以及更新后的Last-Modified参数。
除了Last-Modified/If-Modified-Since
参数外,ETag/If-None-Match参数也常被用于缓存的校验,当客户端请求数据时,服务端会返回数据以及ETag信息,ETag为资源在服务端的唯一标识,客户端再次请求数据的时候将会把标识信息放在If-None-Match参数中向服务端发起校验,如果缓存可用则返回304状态码,否则返回接口数据以及更新后的ETAG信息。
在Http协议中,有很多种缓存的规则,这些缓存规则通过head中Cache-Control的指令来决定,Cache-Control指令以及含义如下所示:
讲完缓存相关的基础知识后我们看一下OKhttp中如何使用缓存以及核心源码:
Okhttp 缓存的设置是比较简单的,指定缓存文件的路径以及缓存文件的最大值即可
//缓存文件夹
File cacheFile = new File(getExternalCacheDir().toString(),"cache");
//缓存大小
int cacheSize = 10 * 1024 * 1024;
//创建缓存对象
Cache cache = new Cache(cacheFile,cacheSize);
//设置缓存
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.build();
缓存的策略定制需要通过cachecontrol来设置
final CacheControl.Builder builder = new CacheControl.Builder();
builder.maxAge(100, TimeUnit.MILLISECONDS); // 设置缓存的最大有效时间为100毫秒
CacheControl cache = builder.build();
final Request request = new Request.Builder().cacheControl(cache).url(requestUrl).build();
final Call call = mOkHttpClient.newCall(request);//
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e
{
Log.e(TAG, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e(TAG, "response ----->" + string);
}
});
return call;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
接下来我们来分析一下缓存相关的核心源码:
首先我们介绍一下相关的几个核心类,然后详细分析其中的核心代码:
CacheInterceptor:缓存拦截器,继承自拦截器接口,负责拦截处理网络请求,
@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; // 通过CacheStrategy处理得到的缓存响应数据
if (cache != null) {
cache.trackResponse(strategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // 缓存数据不能使用清除此缓存数据
}
// 如果当前网络请求不能使用(在CacheStrategy部分详细解释哪些情况为网络请求不可用)而且缓存数据也不可用,则返回网络请求错误的结果
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 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.
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());
}
}
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;
}
CacheStrategy类主要用于根据Http中的Cache-control协议,它根据取出来的缓存结果与当前发送的Request的header进行策略计算,得到缓存是否可用的结果。
// 策略计算需要传入request与缓存 cacheResponse来进行计算
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(); //取出缓存中的head信息
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);
}
}
}
}
/**
* 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;
}
private CacheStrategy getCandidate() {
// 没有缓存的情况,直接返回包含网络请求的策略结果
if (cacheResponse == null) {
return new CacheStrategy(request, null);
}
// 如果是HTTPS请求,但是缓存数据中不存在握手信息,则返回只包含网络请求的策略结果
if (request.isHttps() && cacheResponse.handshake() == null) {
return new CacheStrategy(request, null);
}
// 如果根据CacheControl参数有no-store, 缓存数据不能被存储,则不能使用此缓存
if (!isCacheable(cacheResponse, request)) {
return new CacheStrategy(request, null);
}
CacheControl requestCaching = request.cacheControl();
// 如果缓存数据的CacheControl 有nocache指令或者需要向服务器端校验后决定是否使用缓存,则返回只包含网络请求的策略结果
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
CacheControl responseCaching = cacheResponse.cacheControl();
// 如果响应一直不会改变,则返回只有缓存响应的策略结果
if (responseCaching.immutable()) {
return new CacheStrategy(null, cacheResponse);
}
// 如果缓存在有效的时间范围内,则使用缓存
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;
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
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.
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);
}