与Retrofit 2并行执行http请求 [英] Execute http request in parallel with Retrofit 2
本文介绍了与Retrofit 2并行执行http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Retrofit 2中实现多个并行请求.我有以下结构可以发出3个请求:
I want to implement multiple parallel request in Retrofit 2. I have the following structure to make 3 request :
HistoricalRApi.IStockChart service=HistoricalRApi.getMyApiService();
//^BVSP,^DJI,^IXIC
Call<HistoricalDataResponseTimestamp> call1= service.get1DHistoricalDataByStock("^IXIC");
Call<HistoricalDataResponseTimestamp> call2= service.get1DHistoricalDataByStock("^DJI");
Call<HistoricalDataResponseTimestamp> call3= service.get1DHistoricalDataByStock("^GSPC");
call1.enqueue(retrofitCallbackAmerica());
call2.enqueue(retrofitCallbackAmerica());
call3.enqueue(retrofitCallbackAmerica());
}
我已经阅读了Retrofit1中的内容,当定义其余适配器时,可以使用.setExecutor定义并行请求,如下所示:
I have read that in Retrofit1, when defining the rest adapter one can define parallel request with .setExecutor like here:
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(END_POINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setExecutors(Executors.newFixedThreadPool(3), null)
.build();
我的问题是我如何在Retrofit 2中实现相同的目标?预先感谢
My question is how can i achieve the same in Retrofit 2? Thanks in advance
推荐答案
感谢Colin Gillespie的链接,我已经实现了Jake Wharton所说的,这就是结果:
Thanks to Colin Gillespie link i have implemented what Jake Wharton says and this is the result:
public static IStockChart getMyApiService() {
OkHttpClient client=new OkHttpClient();
Dispatcher dispatcher=new Dispatcher();
dispatcher.setMaxRequests(3);
client.setDispatcher(dispatcher);
// OkHttpClient client = new OkHttpClient();
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// client.interceptors().add(interceptor);
if(myService ==null){
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://chartapi.finance.yahoo.com/")
.addConverterFactory(JsonpGsonConverterFactory.create())
.client(client)
.build();
myService=retrofit.create(IStockChart.class);
return myService;
} else {
return myService;
}
}
这篇关于与Retrofit 2并行执行http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文