【问题标题】:AsyncHttpClient creates how much threads?AsyncHttpClient 创建了多少线程?
【发布时间】:2023-11-15 22:21:01
【问题描述】:

我在代码中使用异步 http 客户端来异步处理 GET 响应 我可以同时运行 100 个请求。

我只在容器中的 httpClient 实例上使用

@Bean(destroyMethod = "close")
open fun httpClient() = Dsl.asyncHttpClient()

代码看起来像

fun method(): CompletableFuture<String> {
    return httpClient.prepareGet("someUrl").execute()
        .toCompletableFuture()
        .thenApply(::getResponseBody)
}

它在功能上运行良好。在我的测试中,我使用具有相同 url 地址的模拟端点。但我的期望是所有请求都在多个线程中处理,但在分析器中我可以看到为 AsyncHttpClient 创建了 16 个线程,并且即使没有要发送的请求,它们也不会被销毁。

我的期望是

  • 异步客户端的线程会更少
  • 线程将在一些配置的超时后被销毁
  • 是否有一些选项可以控制 asyncHttpClient 可以创建多少线程?

我是否错过了我的期望?

更新 1 我在https://github.com/AsyncHttpClient/async-http-client/wiki/Connection-pooling 上看到了说明 我没有找到关于线程池的信息

更新 2 我还创建了方法来做同样的事情,但使用处理程序和额外的执行程序池

实用方法的样子

fun <Value, Result> CompletableFuture<Value>.handleResultAsync(executor: Executor, initResultHandler: ResultHandler<Value, Result>.() -> Unit): CompletableFuture<Result> {
    val rh = ResultHandler<Value, Result>()
    rh.initResultHandler()

    val handler = BiFunction { value: Value?, exception: Throwable? ->
        if (exception == null) rh.success?.invoke(value) else rh.fail?.invoke(exception)
    }

    return handleAsync(handler, executor)
}

更新后的方法看起来像

fun method(): CompletableFuture<String> {
    return httpClient.prepareGet("someUrl").execute()
        .toCompletableFuture()
        .handleResultAsync(executor) {
            success = {response ->
                logger.info("ok")
                getResponseBody(response!!)
            }
            fail = { ex ->
                logger.error("Failed to execute request", ex)
                throw ex
            }
    }
}

然后我可以看到GET方法的结果是在线程池提供的线程中执行的(之前的结果是在“AsyncHttpClient-3-x”中执行的),但是AsyncHttpClient的附加线程仍然被创建并没有被销毁。

【问题讨论】:

  • github.com/AsyncHttpClient/async-http-client/wiki/… 描述了如何设置连接池和线程池
  • 我看到了页面,但没有关于胎面池的内容?
  • 你检查过*.com/questions/35431414/… 吗?
  • 是的,但仍然无法理解它与线程数的关系。所以在我的情况下,我只有一个主机请求。所以在提供的链接中写着应该只有一个线程,可以处理所有请求。或者所有线程都默认初始化,可以被 AsyncClient 用来执行它的内部工作?

标签: multithreading kotlin completable-future asynchttpclient


【解决方案1】:

AHC 有两种类型的线程:

  1. 用于 I/O 操作。 在你的屏幕上,它是 AsyncHttpClient-x-x 线程。 AHC 会创建其中的 2*core_number 个。
  2. 用于超时。 在您的屏幕上,它是 AsyncHttpClient-timer-1-1 线程。应该 只有一个

来源:GitHub 上的问题:https://github.com/AsyncHttpClient/async-http-client/issues/1658

【讨论】:

  • 非常感谢。这完全描述了分析器线程图片,因为我在机器上有 8 个内核,代码在其上执行