Okhttp的缓存机制,四面阿里Android开发岗

   //如果请求里有最大持续时间要求,则取较小的值作为上次响应的刷新时间
  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;
  //获取缓存响应头中的CacheControl信息
  CacheControl responseCaching = cacheResponse.cacheControl();
  //如果缓存响应不是必须要再验证,并且请求有最大过期时间,则用请求的最大过期时间作为最大过期时间
  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());
  }

  //构造一个新的有条件的Request,添加If-None-Match,If-Modified-Since等信息
  Request.Builder conditionalRequestBuilder = request.newBuilder();

  if (etag != null) {
    conditionalRequestBuilder.header("If-None-Match", etag);
  } else if (lastModified != null) {
    conditionalRequestBuilder.header("If-Modified-Since", lastModifiedString);
  } else if (servedDate != null) {
    conditionalRequestBuilder.header("If-Modified-Since", servedDateString);
  }

  Request conditionalRequest = conditionalRequestBuilder.build();
  //根据是否有If-None-Match,If-Modified-Since信息,返回不同的缓存策略
  return hasConditions(conditionalRequest)
      ? new CacheStrategy(conditionalRequest, cacheResponse)
      : new CacheStrategy(conditionalRequest, null);
}

/**
 * Returns true if the request contains conditions that save the server from sending a response
 * that the client has locally. When a request is enqueued with its own conditions, the built-in
 * response cache won't be used.
 */
private static boolean hasConditions(Request request) {
  return request.header("If-Modified-Since") != null || request.header("If-None-Match") != null;
}

}


### Cache

对外开放的缓存类,类似数据库能够增删改查

1.  增添缓存

CacheRequest put(Response response) {
String requestMeth

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值