Okhttp 中的并发连接

问题描述 投票:0回答:1

我在android应用程序中使用okhttp。我在并行进行多个调用时遇到一个非常奇怪的问题。如果我在应用程序刚启动时一次拨打多个电话。有时,第二个调用将延迟启动,而不是所有调用并行进行。但是,如果我继续增加通话次数。大多数呼叫将同时开始,少数呼叫将延迟开始。

lifecycleScope.launch {
            delay(5000)
            val jobs= (0 until 2).map {
               async { homeRemoteDataSource.getEnums() }
            }
            jobs.awaitAll()
        }  

好的http客户端

val client = OkHttpClient().newBuilder()
        client.connectTimeout(60, TimeUnit.SECONDS)
        client.readTimeout(60, TimeUnit.SECONDS)
        client.addInterceptor(authorization)
        client.addInterceptor(contentType)
        client.dispatcher(Dispatcher().apply {
            maxRequests = 100
            maxRequestsPerHost = 100
        })
        client.connectionPool(ConnectionPool(maxIdleConnections = 10, keepAliveDuration = 5,TimeUnit.MINUTES))
        client.build()

android concurrency retrofit2 okhttp
1个回答
0
投票

试试这个:

val client = OkHttpClient.Builder()
       .connectTimeout(60, TimeUnit.SECONDS)
       .readTimeout(60, TimeUnit.SECONDS)
       .addInterceptor(authorization)
       .addInterceptor(contentType)
       .dispatcher(Dispatcher().apply {
            maxRequests = 100
            maxRequestsPerHost = 100
        })
       .connectionPool(ConnectionPool(maxIdleConnections = 10, keepAliveDuration = 5,TimeUnit.MINUTES))
       .build()
© www.soinside.com 2019 - 2024. All rights reserved.