How to speed up parallel queries using Retrofit / OkHttp?

I need to make 50 HTTP GET requests as fast as possible using Retrofit in Android. I am using Retrofit with OkHttp. Currently, Retrofit does a poor job against plain Java ThreadPoolExecutorand HttpUrlConnection: about 50 seconds for Retrofit and 30 seconds for simple HttpUrlConnectionfor all 50 requests, if I set the pool size to 20 for ThreadPoolExecutorand to retrofit / OkHttp I installed okHttpClient.dispatcher().setMaxRequests(20);.

If I look at logcat, I can see that Retrofit executes a maximum of 5 concurrent requests, regardless of what I set to setMaxRequests(), and with ThreadPoolExecutoras many concurrent requests as there are workflows available.

Is there anything I can do to make Retrofit faster? I do not want to switch to HttpUrlConnectionbecause Retrofit is so elegant and easy to use.

Change 1

I tried providing a custom one ThreadPoolExecutorfor OkHttp, but without improving the time:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
ExecutorService exec = new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, new LinkedBlockingQueue<>());
Dispatcher d = new Dispatcher(exec);
builder.dispatcher(d);
OkHttpClient okHttpClient = builder.build();
okHttpClient.dispatcher().setMaxRequests(20);

Edit 2

I make all requests to the same endpoint, if that matters

+4
source share
1 answer

Since they all go to the same host, you tried:

okHttpClient.dispatcher().setMaxRequestsPerHost(20);

Dispatcher.setMaxRequestsPerHost

+5
source

Source: https://habr.com/ru/post/1668411/


All Articles