我需要为不同的端点设置不同的缓存时间,最佳实践是什么?
这是我的改装界面:
public interface ServerApi {
@GET("a1")// need to get 10 mintuns cache time
Observable<A1> getA1();
@GET("a2")// need to get 20 mintuns cache time
Observable<A2> getA2();
@GET("a3")// need to get 30 mintuns cache time
Observable<A3> getA3();
这是我的网络课程:
public class Network {
Network() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(logging)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
retrofit.create(ServerApi.class);
}}
最佳答案
如果服务器提供了正确的缓存控制头。okhttp将为您处理缓存。
改造客户端的init缓存
int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(app.getCacheDir(), cacheSize);
构建okhttp客户端,提供缓存
OkHttpClient client = new OkHttpClient.Builder()
// Add cache
.cache(cache)
.build();
建筑改造
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory
.createWithScheduler(Schedulers.newThread()))
// Add OkHttp client
.client(client)
.build();
如果由于某种原因服务器不提供缓存头。您始终可以硬编码请求拦截器并在客户端添加缓存头。
你也许可以把这些结合起来:
Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>]
但如果你决定这么做,问一个简单的问题。如果我决定更改过期时间怎么办?你可能会写一些不必要的代码或者发布一个新的apk版本。不酷。
祝你好运。
关于android - 改造2-如何为不同的端点设置动态缓存时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47471405/