簡體   English   中英

如何使用 Retrofit / OkHttp 更快地發出並發請求?

[英]How can I make concurrent requests faster with Retrofit / OkHttp?

我需要使用 Android 中的 Retrofit 盡快發出 50 個 http GET 請求。 我正在使用帶有 OkHttp 的 Retrofit。 Currently Retrofit is doing a poor job vs plain Java ThreadPoolExecutor and HttpUrlConnection : about 50sec for Retrofit and 30sec for plain HttpUrlConnection for all 50 requests, if I set the pool size 20 for ThreadPoolExecutor and for Retrofit / OkHttp I set okHttpClient.dispatcher().setMaxRequests(20); .

如果我查看 logcat,我可以看到 Retrofit 最多執行 5 個並發請求,無論我在setMaxRequests()中設置什么,而使用ThreadPoolExecutor時,並發請求的數量與可用的工作線程一樣多。

我能做些什么來讓 Retrofit 更快嗎? 我不想切換到HttpUrlConnection因為 Retrofit 是如此優雅且易於使用。

編輯 1

我嘗試向 OkHttp 提供自定義ThreadPoolExecutor但沒有時間改進:

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

編輯 2

如果這很重要,我會向同一個端點發出所有請求

既然他們都去了同一個主人,你試過:

okHttpClient.dispatcher().setMaxRequestsPerHost(20);

Dispatcher.setMaxRequestsPerHost

dispatcher.maxRequests = 20dispatcher.maxRequestsPerHost = 20都為我完成了這項工作

以一些 Kotlin 為例

package com.package



/**
 * Created by touhid on 24/Jan/2022.
 */
object NetworkService {

    private val interceptor = HttpLoggingInterceptor().apply {
        apply { level = HttpLoggingInterceptor.Level.BODY }
    }
    private val okClient = OkHttpClient.Builder()
        .addInterceptor { chain ->

            val token = getToken(chain)
            var newRequest = chain.request().newBuilder()
            token?.let {
                newRequest = newRequest.addHeader("Authorization", "Bearer $it")
                newRequest = newRequest.addHeader("Accept", "application/json")
            }
            chain.proceed(newRequest.build())
        }
        .addInterceptor(interceptor)

        .build().also {
            it.dispatcher.maxRequests = 20
            it.dispatcher.maxRequestsPerHost = 20
        }


    private val retrofit = Retrofit.Builder()
        .client(okClient)
        .baseUrl(Constants.baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val service: myApiService = retrofit.create(FoodicsApi::class.java)

    

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM