Retrofit 源码解读之离线缓存策略的实现

Retrofit 源码解读之离线缓存策略的实现

Retrofit 是square公司开发的一款网络框架,也是至今Android网络请求中最火的一个,配合Http+RxJava+Retrofit三剑客更是如鱼得水,公司项目重构时,我也在第一时间使用了ReJava+Retrofit,使用过程中遇到的一些问题,也会在后续的博客中,一点点分享出来,供大家参考!

在项目的过程中,项目需求需要在离线的情况下能够继续浏览app内容,第一时间想到缓存,于是经过各种google搜索,得出以下接君(使用Retrofit 2.0)

-参考stackoverflow地址 ,Retrofit 2.0开始,底层的网络连接全都依赖于OkHttp,故要设置缓存,必须从OkHttp下手

-具体的使用过程为:1.先开启OkHttp缓存

File httpCacheDirectory = new File(UIUtils.getContext().getExternalCacheDir(), "responses"); client.setCache(new Cache(httpCacheDirectory,10 * 1024 * 1024));

我们可以看到 先获取系统外部存储的缓存路径,命名为response,此文件夹可以在android/data/<包名>/cache/resposes看到里面的内容,具体OkHttp是如何做到离线缓存的呢?

我们进入Cache类,有重大发现,首先是它的注释,极其详细

Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth. Cache Optimization To measure cache effectiveness, this class tracks three statistics: Request Count: the number of HTTP requests issued since this cache was created. Network Count: the number of those requests that required network use. Hit Count: the number of those requests whose responses were served by the cache. Sometimes a request will result in a conditional cache hit. If the cache contains a stale copy of the response, the client will issue a conditional GET. The server will then send either the updated response if it has changed, or a short \'not modified\' response if the client\'s copy is still valid. Such responses increment both the network count and hit count. The best way to improve the cache hit rate is by configuring the web server to return cacheable responses. Although this client honors all HTTP/1.1 (RFC 7234) cache headers, it doesn\'t cache partial responses. Force a Network Response In some situations, such as after a user clicks a \'refresh\' button, it may be necessary to skip the cache, and fetch data directly from the server. To force a full refresh, add the no-cache directive: Request request = new Request.Builder() .cacheControl(new CacheControl.Builder().noCache().build()) .url("http://publicobject.com/helloworld.txt") .build(); If it is only necessary to force a cached response to be validated by the server, use the more efficient max-age=0 directive instead: Request request = new Request.Builder() .cacheControl(new CacheControl.Builder() .maxAge(0, TimeUnit.SECONDS) .build()) .url("http://publicobject.com/helloworld.txt") .build(); Force a Cache Response Sometimes you\'ll want to show resources if they are available immediately, but not otherwise. This can be used so your application can show something while waiting for the latest data to be downloaded. To restrict a request to locally-cached resources, add the only-if-cached directive: Request request = new Request.Builder() .cacheControl(new CacheControl.Builder() .onlyIfCached() .build()) .url("http://publicobject.com/helloworld.txt") .build(); Response forceCacheResponse = client.newCall(request).execute(); if (forceCacheResponse.code() != 504) { // The resource was cached! Show it. } else { // The resource was not cached. } This technique works even better in situations where a stale response is better than no response. To permit stale cached responses, use the max-stale directive with the maximum staleness in seconds: Request request = new Request.Builder() .cacheControl(new CacheControl.Builder() .maxStale(365, TimeUnit.DAYS) .build()) .url("http://publicobject.com/helloworld.txt") .build(); The CacheControl class can configure request caching directives and parse response caching directives. It even offers convenient constants CacheControl.FORCE_NETWORK and CacheControl.FORCE_CACHE that address the use cases above.

文档详细说明了此类的作用,支持Http缓存使用,然后具体的用法,可惜的是我们这里使用的是Retrofit,无法直接用OkHttp,如果直接用OkHttp的童鞋们,可以根据上面的提示,完成具体的缓存操作。

通过阅读文档,我们知道还有一个类,CacheControl类,只要负责缓存策略的管理,其中,支持一下策略

1. noCache 不使用缓存,全部走网络 2. noStore 不使用缓存,也不存储缓存 3. onlyIfCached 只使用缓存 4. maxAge 设置最大失效时间,失效则不使用 需要服务器配合 5. maxStale 设置最大失效时间,失效则不使用 需要服务器配合 感觉这两个类似 还没怎么弄清楚,清楚的同学欢迎留言 6. minFresh 设置有效时间,依旧如上 7. FORCE_NETWORK 只走网络 8. FORCE_CACHE 只走缓存

通过上面的CacheControl类,我们很快就能指定详细的策略

首先,判断网络,有网络,则从网络获取,并保存到缓存中,无网络,则从缓存中获取

所以,最终的代码如下

-首先,给OkHttp设置拦截器

client.interceptors().add(interceptor);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwpgzx.html