之前写了一篇文章介绍浏览器的HTTP的缓存机制:浏览器HTTP缓存机制
不同于浏览器,客户端需要网络框架来实现缓存机制,今天我们就来研究下Okhttp的缓存机制;
如何使用缓存(CacheControl)
OKhttp提供了一批可以选择的缓存策略,通过CacheControl进行统一配置,通过构造函数我们就可以看出缓存策略。
private CacheControl(boolean noCache, boolean noStore, int maxAgeSeconds, int sMaxAgeSeconds,
boolean isPrivate, boolean isPublic, boolean mustRevalidate, int maxStaleSeconds,
int minFreshSeconds, boolean onlyIfCached, boolean noTransform, boolean immutable,
@Nullable String headerValue) {
}
参数 | 含义 |
---|---|
noCache | 并不意味着不缓存。实际上,在每次请求中使用任何缓存响应之前,它都意味着“使用服务器重新验证” |
noStore | 所有内容都不会缓存,强制缓存,对比缓存都不会触发 |
maxAgeSeconds | 缓存的内容将在 xxx 秒后失效,缓存有效期 |
sMaxAgeSeconds | 和maxAgeSeconds区分开,这个标识共享缓存的有效期 |
isPrivate | 仅客户端可以缓存,代理层不可以访问 |
isPublic | 客户端和代理服务器都可缓存 |
mustRevalidate | 表示在一个缓存过期之后,不能直接使用这个过期的缓存,必须校验之后才能使用,因为存在一些场景下可以使用过期缓存 |
maxStaleSeconds | 表示客户端愿意接受超过其新鲜度生命周期的响应,只超过了maxAgeSeconds之后额外的时间,一般缓存生效时间(maxAgeSeconds + maxStaleSeconds) |
minFreshSeconds | min-fresh 要求缓存服务器返回 min-fresh 时间内的缓存数据。比如,有个资源在缓存里面已经存了7s了,其中 “max-age=10”,那么“7+1<10”,在 1s 之后还是新鲜的,因此是有效的 |
onlyIfCached | 只使用缓存里面的数据,如果没有缓存数据,则返回504 |
immutable | 不可变的 |
使用样例:
Request request = new Request.Builder()
.url(httpUrl)
//缓存策略,强制缓存
.cacheControl(CacheControl.FORCE_CACHE)
.build();
当我们开启缓存的是时候,在缓存目录我们可以看到以下文件:
我们看下其中一些文件内容:
journal文件
59b20da873a6f4c405e64ad3e29a24e9.0 文件
59b20da873a6f4c405e64ad3e29a24e9.1
可以看到一些网络请求的相关一些头信息,和响应body体一些信息,这就是缓存文件也是缓存实现的主要机制;
CacheInterceptor
OKhttp的缓存实现是通过CacheInterceptor 来实现,位于RetryAndFollowUpInterceptor 和 BridgeInterceptor 之后,在真正进行网络连接,网络请求的拦截器之前。
@Override public Response intercept(Chain chain) throws IOException {
// 1. 缓存里面获取备用Response
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
// 2. 根据上述备用Response、缓存策略、请求等来获取当前的网络请求Request对象和缓存Response对象
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
//3. 追踪当前缓存命中次数,以及网络请求次数,用于记录
if (cache != null) {
cache.trackResponse(strategy);
}
// 4. 当备用缓存不可用,关掉备用缓存
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// 5. 不允许使用网络请求 而且 缓存结果是无效的,直接构建Response(code 504)
// 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();
}
// 6. 如果不允许使用网络,且缓存可用,则直接返回缓存结果。
// If we don't need the network, we're done.
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
// 7. 开始执行后续拦截器,开始真正的网络请求;
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());
}
}
// 8. 这里判断如果云端资源是没有发生变化的,即code为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();
// 9. 响应实体没有发生改变,需要更新缓存为最新的响应结果
// 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());
}
}
// 10. 构建最终Response,如果可以缓存,存入缓存中。
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.
// 11. 将网络请求写入缓存,并返回一个可以写入的Response,在读取的时候将缓存写入缓存文件中。
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
//12. 下面一些http请求方法时缓存是无效,需要删除缓存数据
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
public static boolean invalidatesCache(String method) {
return method.equals("POST")
|| method.equals("PATCH")
|| method.equals("PUT")
|| method.equals("DELETE")
|| method.equals("MOVE"); // WebDAV
}
总体路程如下:
- 先从缓存里面获取备用Response;
- 根据上述备用Response、缓存策略、请求等来获取当前的网络请求Request对象和缓存Response对象;
- 追踪当前缓存命中次数,以及网络请求次数,用于记录;
- 当备用缓存不可用,关掉备用缓存;
- 不允许使用网络请求 而且 缓存结果是无效的,直接构建Response(code 504);
- 如果不允许使用网络,且缓存可用,则直接返回缓存结果;
- 开始执行后续拦截器,开始真正的网络请求;
- 判断如果云端资源是没有发生变化的,即code为304,直接使用缓存结果;
- 云端响应实体没有发生改变,需要更新缓存为最新的响应结果;
- 构建最终Response,如果可以缓存,存入缓存中;
- 将网络请求写入缓存,并返回一个可以写入的Response,在读取的时候将缓存写入缓存文件中;
- 下面一些http请求方法时缓存是无效,需要删除缓存数据
Cache (读取)
在上述第一步中,我们看到有一个InternalCache 类型 Cache的成员变量, 我们看下Cache 的中如何获取缓存的。
@Nullable Response get(Request request) {
//1. 根据Url 生成唯一的key值;
String key = key(request.url());
DiskLruCache.Snapshot snapshot;
Entry entry;
try {
//2. 从cache(DiskLruCache)中获取 缓存快照
snapshot = cache.get(key);
if (snapshot == null) {
return null;
}
} catch (IOException e) {
// Give up because the cache cannot be read.
return null;
}
//3. 构建Entry对象,从cache中读取METADATA数据(像url,请求方法,协议,证书,返回码等信息)
try {
entry = new Entry(snapshot.getSource(ENTRY_METADATA));
} catch (IOException e) {
Util.closeQuietly(snapshot);
return null;
}
// 4. 根据缓存数据,构建response
Response response = entry.response(snapshot);
if (!entry.matches(request, response)) {
Util.closeQuietly(response.body());
return null;
}
return response;
}
这里缓存数据使用了一个DiskLruCache,这一次暂时不深入分析DiskLruCache的实现。
- 缓存的key 根据url 生成唯一标识(将url md5加密之后,再进行16进制转换后生成)
- 从cache(DiskLruCache)中获取缓存快照DiskLruCache.Snapshot ;这里介绍三个类的具体功能
- Entry:条目,也就是一个数据条目,可以读取的缓存数据,也可以是将要写入的缓存数据;
- DiskLruCache.Snapshot 缓存快照,提供一个条目的读取和写入等操作;
- DiskLruCache.Editor 缓存编辑器,用于编辑Entry内部的数据,包括写入和读取操作。
- 从Cache文件中构建Entry,主要用于读取缓存文件中的头信息,类似下方:
* { * http://google.com/foo * GET * 2 * Accept-Language: fr-CA * Accept-Charset: UTF-8 * HTTP/1.1 200 OK * 3 * Content-Type: image/png * Content-Length: 100 * Cache-Control: max-age=600 * }
- 根据读取已经读取的缓存数据,构建Response对象。
CacheStrategy (缓存策略)
上面已经根据缓存文件读取到所需的数据,但是到底要不要使用缓存,还有我们配置的缓存策略如何生效,都由CacheStrategy控制。 先看下构建CacheStrategy 的方式
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
首先构造Factory对象,读取缓存Response中缓存相关的响应头数据。
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);
}
}
}
}
下面的逻辑是缓存机制和缓存策略生效的关键。
public CacheStrategy get() {
CacheStrategy candidate = getCandidate();
// 如果不允许使用网络,且缓存是不可用的时候,直接返回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;
}
private CacheStrategy getCandidate() {
// 不存在缓存数据,直接返回
if (cacheResponse == null) {
return new CacheStrategy(request, null);
}
// https请求,没有握手数据,不使用缓存数据
// Drop the cached response if it's missing a required handshake.
if (request.isHttps() && cacheResponse.handshake() == null) {
return new CacheStrategy(request, null);
}
// 判断当前缓存结果是否可用,根据响应code 和 响应头判断,具体哪些code码可以缓存可以参考代码
// 如果在请求头或者响应头中存在“no-store”,则也不使用缓存
if (!isCacheable(cacheResponse, request)) {
return new CacheStrategy(request, null);
}
// 这里判断如果配置了no-cache,或者 请求头中存在“If-Modified-Since”或者“If-None-Match”,都不使用缓存。
CacheControl requestCaching = request.cacheControl();
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
//
CacheControl responseCaching = cacheResponse.cacheControl();
// 缓存响应的当前的年龄,也就是缓存存在的时间
long ageMillis = cacheResponseAge();
// 缓存多久后失效,缓存的有效期
long freshMillis = computeFreshnessLifetime();
if (requestCaching.maxAgeSeconds() != -1) {
freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
}
// 最小缓存,要求缓存服务器返回 min-fresh 时间内的缓存数据
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
// maxStaleMillis 表示客户端愿意接受超过其新鲜度生命周期的响应
long maxStaleMillis = 0;
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
//ageMillis + minFreshMillis < freshMillis + maxStaleMillis
// 表示,当前缓存的存在的时间 小于 缓存有效期和,返回缓存数据。
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());
}
// 判断当前缓存的响应头的条件是否满足,如果满足则返回缓存Reponse,否则正常进行网络请求。
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);
}
上述根据request和缓存reponse对象,根据用户配置的缓存策略以及响应头相关的缓存策略信息进行一系列的判断,来决定是否使用缓存数据,并构建了一个缓存策略对象,中间涉及到的缓存相关缓存头信息,请参照本章开头说明。 主要涉及到如下逻辑
- “no-store” :如果在请求头或者响应头中存在“no-store”,则也不使用缓存
- “no-cache” : 缓存配置了no-cache,或者 请求头中存在“If-Modified-Since”或者“If-None-Match”,都不使用缓存。
- 主要涉及到"max-age","min-fresh","nax-stale"等:要满足ageMillis + minFreshMillis < freshMillis + maxStaleMillis,缓存才可用;
- “If-None-Match”,“ETag”,“If-Modified-Since”:涉及到服务端缓存,决定服务端是否要返回304,这一块逻辑可以参考浏览器缓存的逻辑。
缓存处理
当旺根据缓存配置策略构建出来缓存策略对象,后续的逻辑就回到CacheInterceptor:
5. 不允许使用网络请求 而且 缓存结果是无效的,直接构建Response(code 504);
6. 如果不允许使用网络,且缓存可用,则直接返回缓存结果;
7. 开始执行后续拦截器,开始真正的网络请求;
8. 判断如果云端资源是没有发生变化的,即code为304,直接使用缓存结果;
9. 云端响应实体没有发生改变,需要更新缓存为最新的响应结果;
10. 构建最终Response,如果可以缓存,存入缓存中。
11. 将网络请求写入缓存,并返回一个可以写入的Response,在读取的时候将缓存写入缓存文件中。
12. 当一些http请求方法时缓存是无效(POST,MOVE,PUT,PATCH,DELETE),需要删除缓存数据。
缓存写入逻辑
@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;
}
// 非GET请求,不写入缓存
if (!requestMethod.equals("GET")) {
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;
}
}