OkHttp的CacheInterceptor缓存拦截器剖析
2019-01-29 本文已影响0人
几行代码
OkHttp的桥拦截器的源码解读传送门:https://www.jianshu.com/p/20bfab62c3cd
OkHttp有自己的一套缓存,其实最终还是使用DiskLruCache进行缓存,通过Okhttp内部的线程池对缓存进行保存清除等操作的。
/** Serves requests from the cache and writes responses to the cache.
*
* 服务来自缓存的请求并将响应写入缓存
*/
public final class CacheInterceptor implements Interceptor {
final InternalCache cache;
public CacheInterceptor(InternalCache cache) {
this.cache = cache;
}
@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 (cache != null) {
cache.trackResponse(strategy); // 更新缓存策略
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// If we're forbidden from using the network and the cache is insufficient, fail.
// 当前不能使用网络,也没有找到相应的缓存,这时候会构造出一个Response,抛出一个504异常
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 {
// 通过调用拦截器的方法进行网络请求获取,具体的网络工作交给下一个拦截器来做的,下一个拦截器其实就是ConnectInterceptor
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.
// 接收到网络结果,如果响应code式304,则使用缓存,返回缓存结果
if (cacheResponse != null) {
if (networkResponse.code() == HTTP_NOT_MODIFIED) { // 返回的code为304时,表示得从缓存中获取
.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;
}
缓存的存取都是在这个类Cache中操作的:
Cache缓存请求数据和响应数据,通过内部类CacheRequestImpl来实现CacheInterceptor缓存拦截器的缓存的写入读取操作。
get方法:
/**
* 获取响应体数据的方法
* @param request
* @return
*/
@Nullable Response get(Request request) {
String key = key(request.url());
// 最终还是使用DiskLruCache进行缓存,通过Okhttp内部的线程池对缓存进行保存清除等操作的
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;
}
涉及到的key方法:
// 对请求的url进行md5处理,并进行16进制转换
public static String key(HttpUrl url) {
return ByteString.encodeUtf8(url.toString()).md5().hex();
}
put方法:
/**
* 缓存存入数据的方法
* @param response
* @return
*/
@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")) { // Get请求
// Don't cache non-GET responses. We're technically allowed to cache
// HEAD requests and some POST requests, but the complexity of doing
// so is high and the benefit is low.
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;
}
}
谢谢阅读,如有错误,欢迎指正。
OkHttp的ConnectInterceptor连接拦截器剖析:https://www.jianshu.com/p/f90aa5894cdf