OkHttp3源码分析-缓存与CacheInterceptor

基本结构

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

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

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

Cache的类图:

接下来先分析Cache的源码,CacheStrategy源码,最后是CacheInterceptor源码。

Cache

public final class Cache implements Closeable, Flushable {
    final InternalCache internalCache = new InternalCache() {
    	@Override public Response get(Request request) throws IOException {
      		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);
    	}
  	};
}

InternalCache的实现是匿名内部类,并且是通过调用Cache的相关方法来实现的。

public final class Cache implements Closeable, Flushable { 
    final DiskLruCache 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);
  	}
}

通过构造方法来创建DiskLruCache

我们接着分析putget方法。

put方法

public final class Cache implements Closeable, Flushable {
	@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;
   		}
         ......
    }
}

根据请求method,判断是否是无效的缓存。POSTPUT等方法是无法缓存的。

public final class Cache implements Closeable, Flushable {
	@Nullable CacheRequest put(Response response) {
    	if (!requestMethod.equals("GET")) {
      		return null;
    	}

    }
}

GET请求,不支持缓存。因此直接返回null

public final class Cache implements Closeable, Flushable {
    @Nullable CacheRequest put(Response response) {
        ......
		if (HttpHeaders.hasVaryAll(response)) {
      		return null;
    	}
        ......
    }
}

确实是不是包换所有的Vary,也就是Vary头是不是*。如果是,直接返回null

public final class Cache implements Closeable, Flushable {
    @Nullable CacheRequest put(Response response) {
        ......
		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;
    	}
    }
}

首先是创建一个Entry对象(保存了响应的数据)。接着根据url(urlMD5)从DiskLruCache对象cache中获取DiskLruCache.Editor。接着调用Entry对象entrywriteTo写入数据。最后创建一个CacheRequestImpl返回。

其他的问题:

具体写入都是依赖OKio的,可以自行分析一下。

get方法

public final class Cache implements Closeable, Flushable {
    @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) {
      		return null;
   		}
        ......
}

根据url获取key,根据keyDiskLruCache对象cache中获取DiskLruCache.Snapshot。如果snapshotnull说明没有缓存,直接返回null,如果发生了IOException异常,说明是缓存无法读取,直接返回null

public final class Cache implements Closeable, Flushable {
    @Nullable Response get(Request request) {
        ......
        try {
      		entry = new Entry(snapshot.getSource(ENTRY_METADATA));
    	} catch (IOException e) {
      		Util.closeQuietly(snapshot);
      		return null;
    	}
        ......
    }
}

这段代码主要是创建Entry对象。会从Source中读取urlmethod等信息。

public final class Cache implements Closeable, Flushable {
    @Nullable Response get(Request request) {
        ......
        Response response = entry.response(snapshot);
    	if (!entry.matches(request, response)) {
      		Util.closeQuietly(response.body());
      		return null;
    	}
    	return response;
    }
}

调用entryresponse获取响应。然后判断请求与响应是否匹配,不匹配关闭流,返回null。匹配返回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),因此直接返回参数都为nullCacheStrategy。如果不是直接返回CacheStrategy对象candidate

我们一起来分析一下getCandidate方法。由于getCandidate方法代码比较多,我们分段介绍。

public static class Factory {  
    private CacheStrategy getCandidate() {
	  //没有缓存的响应,直接返回
      if (cacheResponse == null) {
        return new CacheStrategy(request, null);
      }

      //如果是Https但是丢失了TSL的握手就直接返回
      if (request.isHttps() && cacheResponse.handshake() == null) {
        return new CacheStrategy(request, null);
      }

      //根据响应的code,判断是否支持缓存,不支持直接返回。
      if (!isCacheable(cacheResponse, request)) {
        return new CacheStrategy(request, null);
      }
      //从请求中获取CacheControl对象,如果CacheControl为noCache,不使用缓存。
      //或者是请求满足一些条件(添加了验证请求If-Modified-Since或者If-None-Match)就直接返回。
      CacheControl requestCaching = request.cacheControl();
      if (requestCaching.noCache() || hasConditions(request)) {
        return new CacheStrategy(request, null);
      }
      ......
    }
}

上面的代码主要是通过一些条件判断,当创建CacheStrategy对象时,只是传入请求Request时,说明是进行网络请求,只传入缓存的Response时,说明使用缓存。当二者都传入时,进行验证请求。

接着分析:

public static class Factory {
    private CacheStrategy getCandidate() {
        ......
        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());
      	}
        ......
	}
}

缓存计算的基本的逻辑如下:

 public static class Factory {    
     private CacheStrategy getCandidate() {
          ......
          //设置验证请求的数据。
          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);
     }
 }

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

CacheInterceptor

public final class CacheInterceptor implements Interceptor {
  	final InternalCache cache;
    @Override public Response intercept(Chain chain) throws IOException {
    	Response cacheCandidate = cache != null
        	? cache.get(chain.request())
        	: null;
        ......
    }
}

显示获取缓存的Response。如果InternalCache对象cachenull,说明是没有设置缓存,也就是说不支持缓存。不为null是,从cache中获取缓存。一般我们使用的是Cache中的匿名内部类变量internalCache。实际操作的还是Cache

public final class CacheInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
        ......
    	long now = System.currentTimeMillis();
		CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), 		cacheCandidate).get();
    	Request networkRequest = strategy.networkRequest;
    	Response cacheResponse = strategy.cacheResponse;
        ······
    }
}

获取缓存策略CacheStrategy对象,我们前面说过,请求Request与响应Response是否存在决定要不要进行网络请求,还是使用缓存。分四种情况:

  1. Request与Response都存在,说明新鲜度已经过期,需要进行验证请求。
  2. 只有Request,说明需要进行网络请求,不使用缓存。
  3. 只有Response,说明不进行网络请求,使用缓存。
  4. Request和Response都不存在,说明是既不进行网络请求,也不使用缓存。
public final class CacheInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
        ······
        if (cacheCandidate != null && cacheResponse == null) {
      		closeQuietly(cacheCandidate.body());
    	}
        ······
    }
}

CacheStrategy对象中缓存响应cacheResponsenull说明不使用缓存,而cacheCandidate又存在,需要关闭缓存cacheCandidate里面的流。

public final class CacheInterceptor implements Interceptor {    
    @Override public Response intercept(Chain chain) throws IOException { 
        ......
        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();
    	}
        ......
    }
}

如果既不用缓存也不使用网络,直接构建响应并返回。

public final class CacheInterceptor implements Interceptor {    
    @Override public Response intercept(Chain chain) throws IOException { 
        ......
		if (networkRequest == null) {
      		return cacheResponse.newBuilder()
          		.cacheResponse(stripBody(cacheResponse))
          		.build();
        }
        ......
    }
}

根据前面的判断,这里可以确定是缓存命中。networkRequestnull说明不进行网络请求,根据缓存构建响应并返回。

public final class CacheInterceptor implements Interceptor {        
    @Override public Response intercept(Chain chain) throws IOException { 
        ......
        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());
            }
    	}
        ......
    }
}

通过Chain责任链获取响应,finally中当获取的响应是null时,并且存在缓存时,关闭缓存中的流。

public final class CacheInterceptor implements Interceptor {        
    @Override public Response intercept(Chain chain) throws IOException { 
         ......
		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());
            }
    	}
        ......
    }
}

cacheResponse != null,说明存在缓存,然后是判断网络的响应的networkResponsecode是否为HTTP_NOT_MODIFIED(304),如果是说明缓存还可以使用,构建Response,并更新缓存,返回。不为HTTP_NOT_MODIFIED,说明内容已经修改,不能使用缓存了,关闭缓存中的流。

public final class CacheInterceptor implements Interceptor {            
    @Override public Response intercept(Chain chain) throws IOException { 
        ......
        Response response = networkResponse.newBuilder()
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();

        if (cache != null) {
          	if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
            	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;    
    }
}

构建响应Response,然后根据需要put缓存。

总结

OkHttp的源码并不难,如果看不懂,大部分原因是Http的缓存的机制不了。

可以查看:

  • https://tools.ietf.org/html/rfc7234
  • 《Http权威指南》

你可能感兴趣的:(Android,开源库,OkHttp3,OkHttp源码分析)