美文网首页
Android OkHttp3流程分析(3)

Android OkHttp3流程分析(3)

作者: Bfmall | 来源:发表于2023-04-13 11:35 被阅读0次

接着上篇:https://www.jianshu.com/p/48f2d6551b6b

3.3 CacheInterceptor缓存拦截器

这个拦截器的作用是缓存,整体的流程都是围绕一个叫缓存策略来的,其中里面有两个重要的参数networkRequest和cacheResponse这两个代表了网络和缓存,通过判断两个参数是否为null来执行网络请求和缓存的策略。

基本结构


image.png

CacheInterceptor依赖两个关键类,一个是CacheStrategy,一个是InternalCache。

CacheStrategy采用的是简单工厂模式(其实只是抽象工厂的特例),此类用于判定使用缓存,网络还是二者都使用。

InternalCache基本不会自己去设置,会使用Cache中的InternalCache的结构,而Cache实际上是通过DiskLruCache实现。

Cache的类图:

image.png
接下来先分析Cache的源码,CacheStrategy源码,最后是CacheInterceptor源码。
//Cache.java
public final class Cache implements Closeable, Flushable {

  //InternalCache的实现是匿名内部类,并且是通过调用Cache的相关方法来实现的。
  final InternalCache internalCache = new InternalCache() {
    @Override public Response get(Request request) throws IOException {
      //调用Cache类的get方法
      return Cache.this.get(request);
    }

    @Override public CacheRequest put(Response response) throws IOException {
      return Cache.this.put(response);
    }

    @Override public void remove(Request request) throws IOException {
      Cache.this.remove(request);
    }

    @Override public void update(Response cached, Response network) {
      Cache.this.update(cached, network);
    }

    @Override public void trackConditionalCacheHit() {
      Cache.this.trackConditionalCacheHit();
    }

    @Override public void trackResponse(CacheStrategy cacheStrategy) {
      Cache.this.trackResponse(cacheStrategy);
    }
  };

  final DiskLruCache cache;

  /**
   * Create a cache of at most {@code maxSize} bytes in {@code directory}.
   */
  public Cache(File directory, long maxSize) {
    this(directory, maxSize, FileSystem.SYSTEM);
  }

  Cache(File directory, long maxSize, FileSystem fileSystem) {
    //通过构造方法来创建DiskLruCache
    this.cache = DiskLruCache.create(fileSystem, directory, VERSION, ENTRY_COUNT, maxSize);
  }
}

我们接着分析put与get方法

Put方法:
//Cache.java
  @Nullable CacheRequest put(Response response) {
    String requestMethod = response.request().method();
    //根据请求method,判断是否是无效的缓存。POST,PUT等方法是无法缓存的。
    if (HttpMethod.invalidatesCache(response.request().method())) {
      try {
        remove(response.request());
      } catch (IOException ignored) {
        // The cache cannot be written.
      }
      return null;
    }
    //非GET请求,不支持缓存。因此直接返回null。
    if (!requestMethod.equals("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;
    }
    //确实是不是包含所有的Vary,也就是Vary头是不是*。如果是,直接返回null
    if (HttpHeaders.hasVaryAll(response)) {
      return null;
    }

    //首先是创建一个Entry对象(保存了响应的数据)。
    Entry entry = new Entry(response);
    DiskLruCache.Editor editor = null;
    try {
      //接着根据url(url的MD5)从DiskLruCache对象cache中获取DiskLruCache.Editor。
      editor = cache.edit(key(response.request().url()));
      if (editor == null) {
        return null;
      }
       //接着调用Entry对象entry的writeTo写入数据。
      entry.writeTo(editor);
      //最后创建一个CacheRequestImpl返回。
      return new CacheRequestImpl(editor);
    } catch (IOException e) {
      abortQuietly(editor);
      return null;
    }
  }
Get方法:
//Cache.java
@Nullable Response get(Request request) {
    //根据url获取key
    String key = key(request.url());
    DiskLruCache.Snapshot snapshot;
    Entry entry;
    try {
      //根据key从DiskLruCache对象cache中获取DiskLruCache.Snapshot。
      snapshot = cache.get(key);
      //如果snapshot为null说明没有缓存,直接返回null
      if (snapshot == null) {
        return null;
      }
    } catch (IOException e) {
      //如果发生了IOException异常,说明是缓存无法读取,直接返回null。
      // Give up because the cache cannot be read.
      return null;
    }

    try {
      //创建Entry对象。会从Source中读取url,method等信息。
      entry = new Entry(snapshot.getSource(ENTRY_METADATA));
    } catch (IOException e) {
      Util.closeQuietly(snapshot);
      return null;
    }
    //调用entry的response获取响应。
    Response response = entry.response(snapshot);
    //然后判断请求与响应是否匹配,不匹配关闭流,返回null。匹配返回Response
    if (!entry.matches(request, response)) {
      Util.closeQuietly(response.body());
      return null;
    }

    return response;
  }
CacheStrategy

CacheStrategy采用的是简单工厂(抽象工厂的特例)。我们先分析CacheStrategy的静态类Factory。

public static class Factory {
   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);
          }
        }
      }
    }
}

构造方法中,主要是解析缓存相关的字段。

Date 报文创建的日期和时间,用于计算新鲜度。
Expires响应失效的日期和时间。
Last-Modified提供实体最后一次修改的时间。
ETag 表示实体的标记。
Age告诉接收端响应已经产生了多长时间。

public static class Factory {  
     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方法获取CacheStrategy对象。

如果是onlyIfCached,由于验证请求不支持onlyIfCached(only-if-cached),因此直接返回参数都为null的CacheStrategy。如果不是直接返回CacheStrategy对象candidate。

我们一起来分析一下getCandidate方法。由于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();
      //计算age,计算的方法见 https://tools.ietf.org/html/rfc7234#section-4.2.3
      long ageMillis = cacheResponseAge();
      //计算新鲜度 https://tools.ietf.org/html/rfc7234#section-4.2.1
      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());
      }
    //获取max-stale,表示过期后能够使用的时间。
      long maxStaleMillis = 0;
      if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
        maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
      }
      //说明没有真正的过期。
      if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
        Response.Builder builder = cacheResponse.newBuilder();
        //发送110警告。
        if (ageMillis + minFreshMillis >= freshMillis) {
          builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
        }
        //启发式过期,需要发送113警告。
        long oneDayMillis = 24 * 60 * 60 * 1000L;
        if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
          builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
        }
        return new CacheStrategy(null, builder.build());
      }

      //设置验证请求的数据。
      // Find a condition to add to the request. If the condition is satisfied, the response body
      // 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 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);
    }

上面代码主要是获取验证请求的数据,并设置到请求中,最终返回策略。

再看下intercept方法:

@Override public Response intercept(Chain chain) throws IOException {
    //显示获取缓存的Response。如果InternalCache对象cache为null,
    //说明是没有设置缓存,也就是说不支持缓存。不为null是,从cache中获取缓存。
   //一般我们使用的是Cache中的匿名内部类变量internalCache。实际操作的还是Cache。
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();

    /**
    *获取缓存策略CacheStrategy对象,我们前面说过,请求Request与响应        
    * Response是否存在决定要不要进行网络请求,还是使用缓存。分四种情况:
    *
    * 1.Request与Response都存在,说明新鲜度已经过期,需要进行验证请求。
    * 2.只有Request,说明需要进行网络请求,不使用缓存。
    * 3.只有Response,说明不进行网络请求,使用缓存。
    * 4.Request和Response都不存在,说明是既不进行网络请求,也不使用缓存。
    *
    */
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;

    if (cache != null) {
      cache.trackResponse(strategy);
    }
   
    //CacheStrategy对象中缓存响应cacheResponse为null说明不使用缓存,
    //而cacheCandidate又存在,需要关闭缓存cacheCandidate里面的流。
    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.
    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();
    }

    //根据前面的判断,这里可以确定是缓存命中。
    // networkRequest为null说明不进行网络请求,根据缓存构建响应并返回。
    Response networkResponse = null;
    try {
      networkResponse = chain.proceed(networkRequest);
    } finally {
       //通过Chain责任链获取响应,finally中当获取的响应是null时,并且存在缓存时,关闭缓存中的流。
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

    /**
     *cacheResponse != null,说明存在缓存,然后是判断网络的响应的        
     *networkResponse的code是否为HTTP_NOT_MODIFIED(304),如果是说明缓 
     *存还可以使用,构建Response,并更新缓存,返回。不为 
     *HTTP_NOT_MODIFIED,说明内容已经修改,不能使用缓存了,关闭缓存中的流。
    *
    */
    // If we have a cache response too, then we're doing a conditional get.
    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();

        // 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 response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        //然后根据需要put缓存。
        // 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;
  }

————————————————
参考:
https://blog.csdn.net/wfeii/article/details/88417745

相关文章

网友评论

      本文标题:Android OkHttp3流程分析(3)

      本文链接:https://www.haomeiwen.com/subject/vrwgddtx.html