gpt4 book ai didi

android - Retrofit 2 - 如何为不同端点设置动态缓存时间

转载 作者:太空狗 更新时间:2023-10-29 13:51:02 26 4
gpt4 key购买 nike

我需要为不同的端点设置不同的缓存时间,最佳做法是什么?

这是我的 Retrofit 界面:

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();

这是我的网络类(class):

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);
}}

最佳答案

如果您的服务器提供正确的缓存控制 header 。 OkHttp 将为您处理缓存。

为您的 Retrofit 客户端初始化缓存

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();

如果由于某种原因您的服务器不提供缓存 header 。您始终可以对请求拦截器进行硬编码并在客户端添加缓存 header 。

你可能会使用这些的一些组合:

Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>]

但如果您决定这样做,请问一个简单的问题。如果我决定更改到期时间怎么办?您可能最终会编写一些不必要的代码或发布新的 APK 版本。不酷。

祝你好运。

关于android - Retrofit 2 - 如何为不同端点设置动态缓存时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47471405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com