限制或限制 Kotlin 协程数量

so-*_*ude 3 rest http kotlin kotlinx.coroutines

我正在尝试从我的协程中访问 http 服务。我可能需要点击该服务一百万次。我更喜欢并行执行,因为它们是彼此独立的,同时我不想 DOS 该服务。我想限制我的协程(某种背压)

我知道我可以将请求批量处理到可接受的并发请求数。但是,我认为这太样板了。是否有任何 http 库以惯用的方式处理这个问题

osh*_*hai 5

选项1:

OK HTTPwithretrofit可以限制请求数量:

Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(100);
dispatcher.setMaxRequestsPerHost(10);
OkHttpClient client = new OkHttpClient.Builder()
    .dispatcher(dispatcher)
    .build();
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看示例:OkHttpClient 限制连接数?
有一个协程适配器:https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter
因此,两者一起将为您提供所需的东西。

选项2:

使用带有AsyncHttpClient适配器的 Retrofit:https://github.com/AsyncHttpClient/async-http-client/tree/master/extras/retrofit2

然后像这样限制资源:

AsyncHttpClient http = asyncHttpClient(config()
    .setMaxConnections(500)
    .setMaxConnectionsPerHost(200)
    .setPooledConnectionIdleTimeout(100)
    .setConnectionTtl(500)
);
Run Code Online (Sandbox Code Playgroud)

该示例来自 wiki: https: //github.com/AsyncHttpClient/async-http-client/wiki/Connection-pooling

选项 3:

使用上述客户端之一(或任何其他客户端),无需改装。然后自己包装回调或找到一个已经这样做的库(存在许多回调类型):https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#wrapping-callbacks