Retrofit2 cache implementation

Why use caching

1. load faster
2. Reduce data usage
3. relieve pressure server
can also access the network when no 4., optimize the user experience

Talk about my needs:
1. When using the cache has a net short period of time, up to date, there is no net when the cache longer
2. Specify the interface generates cache files, other interfaces will not have the cache file
3. Can the drop-down refresh force a refresh

The principle

Retrofit2 implement caching is achieved by natural okhttp blocker, is particularly controlled by the Cache-Control
separately as follows:

      
      
1
2
3
4
5
6
7
8
9
10
11
12
      
      
NO- Cache NO - Cache time will be cached, but each time in response providing data to the client (browser), the cache must assess the effectiveness of the response to the cache server.
NO - Store all content will not be cached in cache or temporary Internet files
max -AGE = xxx (xxx IS numeric ) cached content to xxx seconds after failure, this option is only the HTTP 1.1 is available, and if and Last when used together -Modified, higher priority
max -stale and max -AGE, can only be disposed inside the head request.
And set max -stale and max -AGE, cache miss by the longest time count. (This fact, do not tangle)
CacheControl.FORCE_CACHE mandatory use of the cache, if the data is not cached, then throw 504 ( only - IF -cached)
CacheControl.FORCE_NETWORK forced to use the network, without using any cache.

Simple implementation

1. first create interceptor

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
      
      
static Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
public Response (Chain chain) throws IOException {
Request request = chain.request();
Response response = chain. proceed(request);
if (NetworkUtil.isNetworkAvalible(MyApplication.getContext())) {
int maxAge = 60;
return response.newBuilder()
.removeHeader( "Pragma") //清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
.header( "Cache-Control", "public ,max-age=" + maxAge)
.build();
}
return response;
}
};

2.这样的话就写好了拦截器,然后就是把拦截器设置到okhttp里面

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
      
      
File httpCacheDirectory = new File(MyApplication.getInstance().getExternalCacheDir(), "HttpCache");
大专栏  Retrofit2缓存实现 class="attribute"> int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(httpCacheDirectory, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(cache)
.build();
r e t r o f i t = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();

注意缓存路径要写对,同时注意addNetworkInterceptor和addInterceptor的区别
这样就简单实现了retrofit的缓存,在60秒内可以通过缓存来访问,优化访问速度与体验

不同接口可缓存不同时间,同时可设置是否缓存

从header中获取cache-Control字段,即可实现不同接口缓存不同时间,header中没有cache-control字段时则不缓存

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
      
      
@Headers( "Cache-Control: public, max-age=3600")
@GET( "song/getsonglistsong?id=recommend")
Flowable<SongList> getRecommendList();
static Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
public Response (Chain chain) throws IOException {
Request request = chain.request();
Response response = chain. proceed(request);
if (NetworkUtil.isNetworkAvalible(MyApplication.getContext())) {
String cacheControl =request.cacheControl().toString();
return response.newBuilder()
.removeHeader( "Pragma") //清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
.header( "Cache-Control", cacheControl)
.build();
}
return response;
}
};

Reference links

https://www.cnblogs.com/cxk1995/p/5996586.html
https://blog.csdn.net/adzcsx2/article/details/51365548
https://www.jianshu.com/p/241e6af94390
https://blog.csdn.net/wangkeke1860/article/details/52084869
https://www.jianshu.com/p/9c3b4ea108a7
https://www.cnblogs.com/android-yus/p/5280739.html
https://blog.csdn.net/u010286855/article/details/52608485

Guess you like

Origin www.cnblogs.com/sanxiandoupi/p/11711045.html