上一篇我们讲到拦截器链,还讲解了前两个拦截器RetryAndFollowUpInterceptor和BridgeInterceptor,今天我们要讲解的是CacheInterceptor-----缓存拦截器。
首先我们看看它是如何使用缓存的:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(new Cache(new File("缓存的文件名"), 2 * 1024 * 1024))
.build();
这里是指定了缓存的文件还有就是缓存的大小。这里出现了一个个Cache类,那我们就先看看这个类。
首先看看它的构造方法:
public Cache(File directory, long maxSize) {
this(directory, maxSize, FileSystem.SYSTEM);
}
Cache(File directory, long maxSize, FileSystem fileSystem) {
this.cache = DiskLruCache.create(fileSystem, directory, VERSION, ENTRY_COUNT, maxSize);
}
没错,这里创建了一个DisLruCache的实例并且赋值给cache这个成员变量,所以说我们最终的缓存使用的磁盘缓存。
1. put方法
@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;
}
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;
}
}
这里首先会获取request请求的方法(get,post,put…),然后会调用HttpMethod.invalidatesCache()方法判断请求的方法是否属于以下方法,是的话则会调用remove方法把缓存清除掉,再返回一个null。
public static boolean invalidatesCache(String method) {
return method.equals("POST")
|| method.equals("PATCH")
|| method.equals("PUT")
|| method.equals("DELETE")
|| method.equals("MOVE"); // WebDAV
}
void remove(Request request) throws IOException {
cache.remove(key(request.url()));
}
继续回到Cache的put方法中,第11行这里判断如果不是“GET”方法的话,也没有必要进行缓存。然后到17行这里,出现了Entry这个类,我们看看它的构造方法:
Entry(Response response) {
this.url = response.request().url().toString();
this.varyHeaders = HttpHeaders.varyHeaders(response);
this.requestMethod = response.request().method();
this.protocol = response.protocol();
this.code = response.code();
this.message = response.message();
this.responseHeaders = response.headers();
this.handshake = response.handshake();
this.sentRequestMillis = response.sentRequestAtMillis();
this.receivedResponseMillis = response.receivedResponseAtMillis();
}
没错,这个类就是我们要写入的缓存部分,包括了请求的url,头部信息,请求的方法,协议等等。
创建完这个Entry这个类之后,然后在20行创建了我们的Editor的实例,并且把url这个key作为参数传递进去,而 这个key也是通过key()生成的,它就是把url通过md5加密然后取其16进制。
public static String key(HttpUrl url) {
return ByteString.encodeUtf8(url.toString()).md5().hex();
}
看到第24行entry.writeTo(editor),这个方法就是真正把缓存写进到磁盘中去,我们走进去看看:
public void writeTo(DiskLruCache.Editor editor) throws IOException {
BufferedSink sink = Okio.buffer(editor.newSink(ENTRY_METADATA));
sink.writeUtf8(url)
.writeByte('\n');
sink.writeUtf8(requestMethod)
.writeByte('\n');
sink.writeDecimalLong(varyHeaders.size())
.writeByte('\n');
for (int i = 0, size = varyHeaders.size(); i < size; i++) {
sink.writeUtf8(varyHeaders.name(i))
.writeUtf8(": ")
.writeUtf8(varyHeaders.value(i))
.writeByte('\n');
}
sink.writeUtf8(new StatusLine(protocol, code, message).toString())
.writeByte('\n');
sink.writeDecimalLong(responseHeaders.size() + 2)
.writeByte('\n');
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
sink.writeUtf8(responseHeaders.name(i))
.writeUtf8(": ")
.writeUtf8(responseHeaders.value(i))
.writeByte('\n');
}
sink.writeUtf8(SENT_MILLIS)
.writeUtf8(": ")
.writeDecimalLong(sentRequestMillis)
.writeByte('\n');
sink.writeUtf8(RECEIVED_MILLIS)
.writeUtf8(": ")
.writeDecimalLong(receivedResponseMillis)
.writeByte('\n');
if (isHttps()) {
sink.writeByte('\n');
sink.writeUtf8(handshake.cipherSuite().javaName())
.writeByte('\n');
writeCertList(sink, handshake.peerCertificates());
writeCertList(sink, handshake.localCertificates());
sink.writeUtf8(handshake.tlsVersion().javaName()).writeByte('\n');
}
sink.close();
}
我们就是会缓存这个url,方法,头部信息,遍历头部信息。还有响应行StatusLine,响应的首部信息,发送的时间,接收的时间。最后还会判断是否https。
那么我们的请求主体body在哪里保存呢?答案就是在put方法的
return new CacheRequestImpl(editor).
private final class CacheRequestImpl implements CacheRequest {
private final DiskLruCache.Editor editor;
private Sink cacheOut;
private Sink body;
boolean done;
CacheRequestImpl(final DiskLruCache.Editor editor) {
this.editor = editor;
this.cacheOut = editor.newSink(ENTRY_BODY);
this.body = new ForwardingSink(cacheOut) {
@Override public void close() throws IOException {
synchronized (Cache.this) {
if (done) {
return;
}
done = true;
writeSuccessCount++;
}
super.close();
editor.commit();
}
};
}
....
}
这个类是继承自CacheRequest,这里主要的目的就是为了在CacheInterceptor里面这里直接操作缓存的操作。我们看这个构造方法里面又有一个editor,还有就是我们的body。
2. get方法
@Nullable Response get(Request request) {
String key = key(request.url());
DiskLruCache.Snapshot snapshot;
Entry entry;
try {
snapshot = cache.get(key);
if (snapshot == null) {
return null;
}
} catch (IOException e) {
// Give up because the cache cannot be read.
return null;
}
try {
entry = new Entry(snapshot.getSource(ENTRY_METADATA));
} catch (IOException e) {
Util.closeQuietly(snapshot);
return null;
}
Response response = entry.response(snapshot);
if (!entry.matches(request, response)) {
Util.closeQuietly(response.body());
return null;
}
return response;
}
这里首先也是根据url获取到key,然后就是根据这个key获取到Snapshot(缓存快照),根据这个缓存快照创建Entry的实例,而这个Entry就是我们之前讲put方法的时候保存的缓存信息。然后在第20行,调用entry.response方法利用缓存信息构造出Response,那我们来看看这个方法就清晰了:
public Response response(DiskLruCache.Snapshot snapshot) {
String contentType = responseHeaders.get("Content-Type");
String contentLength = responseHeaders.get("Content-Length");
Request cacheRequest = new Request.Builder()
.url(url)
.method(requestMethod, null)
.headers(varyHeaders)
.build();
return new Response.Builder()
.request(cacheRequest)
.protocol(protocol)
.code(code)
.message(message)
.headers(responseHeaders)
.body(new CacheResponseBody(snapshot, contentType, contentLength))
.handshake(handshake)
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(receivedResponseMillis)
.build();
}
拿到response之后,在Cache类的get方法中的第21行,还要对response和request进行匹配matches,因为一个request对应这个一个response。
public boolean matches(Request request, Response response) {
return url.equals(request.url().toString())
&& requestMethod.equals(request.method())
&& HttpHeaders.varyMatches(response, varyHeaders, request);
}
至此,我们对Okhttp的缓存有了大致了解,这对我们接下来讲解CacheInterceptor有很大的帮助,那我们现在正式讲解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
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
}
// If we're forbidden from using the network and the cache is insuffi
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.
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 ge
if (cacheResponse != null) {
if (networkResponse.code() == HTTP_NOT_MODIFIED) {
Response response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers(), networkResponse.hea
.sentRequestAtMillis(networkResponse.sentRequestAtMillis())
.receivedResponseAtMillis(networkResponse.receivedResponseAtM
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
// Update the cache after combining headers but before stripping
// 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(resp
// 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;
}
这里代码比较长,我们一步步看。首先是根据cache.get(request)里面尝试去获取缓存。第6行这里,创建了一个CacheStrategy的实例,其实它就是我们这里的缓存策略。我们看看这个类:
public final class CacheStrategy {
/** The request to send on the network, or null if this call doesn't use the network. */
public final @Nullable Request networkRequest;
/** The cached response to return or validate; or null if this call doesn't use a cache. */
public final @Nullable Response cacheResponse;
CacheStrategy(Request networkRequest, Response cacheResponse) {
this.networkRequest = networkRequest;
this.cacheResponse = cacheResponse;
}
...
}
原来里面维护着一个request请求和response,其实后面我们就会根据这两个值来判断究竟是使用网络请求还是直接缓存。这里首先是将request和缓存中取出去的response传递到CacheStrategy的Factory内部类中,再调用get()方法创建CacheStrategy实例,那么我们就进去看看这个get方法:
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()方法,我们继续往下看:
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.
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);
}
CacheControl requestCaching = request.cacheControl();
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.maxAgeS
}
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
long maxStaleMillis = 0;
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() !=
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis +
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 expiratio
}
return new CacheStrategy(null, builder.build());
}
// Find a condition to add to the request. If the condition is satisfied, the
// 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 re
}
Headers.Builder conditionalRequestHeaders = request.headers().newBuilder();
Internal.instance.addLenient(conditionalRequestHeaders, conditionName, condit
Request conditionalRequest = request.newBuilder()
.headers(conditionalRequestHeaders.build())
.build();
return new CacheStrategy(conditionalRequest, cacheResponse);
}
这个方法就是真正创建CacheStrategy实例的。
第3行,会对我们的缓存的reponse是否为空进行判断,如果的话,那么我们就要重新建立一个请求连接,所以把request传进去,而respons就是为null了。
第7行,这个请求是不是https并且还没有进行握手的,也会同样重新建立请求。
第13行,这里会判断这个请求是不是可以进行缓存的,如果不可以缓存的话也是会选择网络操作。
第17行,会判断这个请求是不使用缓存或者这个request是一个可选择的http请求,是的话就会重新进行网络请求。
第21行,会判断这个缓存的response是不是不容易被影响,如果是的话,那么创建的CacheStrategy中request是为空的,response是有值的。
第38行,这里会对缓存的response进行添加一些请求头的操作。
这样子就是我们的缓存策略所做的工作。
我们继续回到CacheInterceptor,拿到缓存策略之后,就会分别取出缓存策略的request和response。看到第10行,cache.trackResponse(strategy),我们看看这个方法:
synchronized void trackResponse(CacheStrategy cacheStrategy) {
requestCount++;
if (cacheStrategy.networkRequest != null) {
// If this is a conditional request, we'll increment hitCount if/when it hits.
networkCount++;
} else if (cacheStrategy.cacheResponse != null) {
// This response uses the cache and not the network. That's a cache hit.
hitCount++;
}
}
其实这里只是做一些命中数的统计,还有就是request的累计。
回到CacheInterceptor的第16行,如果networkRequest和cacheResponse都为空,就是说不能使用网络,而且又没有缓存的话,就会返回一个504的Response 。
第28行,如果networkRequest是为空的话,就是说cacheResponse是不为空的,所以就将缓存的response返回。
如果还能继续往下走,就证明networkReuqest是不为空的,此时就会继续调用拦截器链的proceed方法,交给下一个拦截器进行网络访问,获取到networkResponse。
第43行,判断如果此时cacheResonse也不为空的话,就是说缓存策略是同时使用网络跟缓存,此时就会去判断网络请求的这个response的网络状态码是不是304,如果是的话就会使用缓存的resonse,否则的话就会去使用网络的这个response。
如果是最终使用网络的response的话,在第67行就会去判断这个Http头部有没有响应体,Http的缓存策略是否可以缓存,成立的话就会把这个response添加到缓存中。
最后,在72行这里,还要判断这个请求的方法是不是一个无效的缓存方法,如果是的话就还是会把这个response从缓存中移除。
补充:
刚刚有说到304这个网络状态码,这里顺便说一下Http的缓存。其实http的缓存分为两种,强制缓存和对比缓存。
强制缓存
主要由在两个服务端返回的响应的header中有两个字段表明
1、Expires
表示服务端返回的到期时间,当下一次请求的时间小于这个时间的话,就直接使用缓存。
http1.0协议的,这里有个问题就是这个时间是服务端生成的,跟客户端产生的时间可能会有误差,导致缓存读取可能会有误差。
2、Cache-Control
这个字段主要有5个取值
取值 | 含义 |
---|---|
private | 客户端可以缓存 |
public | 客户端和代理服务器都可缓存 |
max-age=xxx | 缓存的内容将在 xxx 秒后失效 |
no-cache | 需要使用对比缓存来验证缓存数据,强制缓存的两个标识无法去使用缓存 |
no-store | 所有内容都不会缓存,强制缓存,对比缓存都不会触发 |
默认是private
对比缓存
需要进行比较判断是否可以使用缓存。浏览器第一次进行访问的时候,服务器会将缓存标识与数据一起返回给客户端
1、Etag / If-None-Match
Etag:服务器响应请求时,服务端告诉浏览器(客户端)当前资源在服务器的唯一标识,生成规则由服务器决定
If-None-Match:再次请求服务器时,告诉服务器客户端缓存这个数据的唯一标识,其实就是之前Etag返回的标识。
服务端收到请求后,如果发现有If-None-Match这个字段,就会把这个标识跟源数据(被请求资源)里面的标识进行对比,如果没有改动过,就返回304,使用缓存;如果改动过,就会返回200,再一次进行请求。
2、Last-Modified / If-Modified-Since
Last-Modified:服务器在响应请求时,告诉浏览器资源最后的修改时间
If-Modified-Since:再次请求的时候,通过此字段告诉服务器上次请求时,服务器返回的资源最后的修改时间。
服务器收到请求后,如果发现有If-Modified-Since这个字段,就会跟被请求资源的最后修改时间进行对比,如果是大于If-Modified-Since,说明资源被修改过,返回200,再次进行请求;如果是小于或者等于(感觉好像不会小于)If-Modified-Since,说明资源没有被修改过,返回304,告知客户端使用缓存。
至此,第三个拦截器CacheInterceptor就讲完了,剩下的两个拦截器会在后面一一讲解,感谢!