OkHttp3源码详解(四)缓存策略

[CacheStrategy.java]

/**

  • Given a request and cached response, this figures out whether to use the network, the cache, or

  • both.

  • Selecting a cache strategy may add conditions to the request (like the “If-Modified-Since”

  • header for conditional GETs) or warnings to the cached response (if the cached data is

  • potentially stale).

_/

public final class CacheStrategy {

/_* The request to send on the network, or null if this call doesn’t use the network. */

public final Request networkRequest;

/** The cached response to return or validate; or null if this call doesn’t use a cache. */

public final Response cacheResponse;

}

CacheStrategy$Factory:缓存策略工厂类根据实际请求返回对应的缓存策略

既然实际的缓存工作都是在CacheInterceptor中完成的,那么接下来看下CahceInterceptor的核心方法intercept方法源码:

[CacheInterceptor.java]

@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);

}

//如果当前缓存不符合要求,将其close

if (cacheCandidate != null && cacheResponse == null) {

closeQuietly(cacheCandidate.body()); // The cache candidate wasn’t applicable. Close it.

}

// 如果不能使用网络,同时又没有符合条件的缓存,直接抛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 (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());

}

}

// 如果既有缓存,同时又发起了请求,说明此时是一个Conditional Get请求

if (cacheResponse != null) {

// 如果服务端返回的是NOT_MODIFIED,缓存有效,将本地缓存和网络响应做合并

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)) {

// 将网络响应写入cache中

CacheRequest c

  • 11
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值