gpt4 book ai didi

Java asyncHttpClient 为每个连接创建新线程

转载 作者:行者123 更新时间:2023-12-01 19:46:49 28 4
gpt4 key购买 nike

我正在用java做库,库用于调用外部服务API。为此,我使用 AsyncHttpClient

部分代码:

 public CompletableFuture<Optional<TokensResponse>> clientCredentialsGrant(String clientId, String clientSecret, String deviceId, Optional<String> scope) {
AsyncHttpClient asyncHttpClient = asyncHttpClient();
BoundRequestBuilder requestBuilder = asyncHttpClient
.preparePost(host + "/oauth2/token")
.addFormParam("grant_type", "client_credentials")
.addFormParam("device_id", deviceId)
.addFormParam("client_id", clientId)
.addFormParam("client_secret", clientSecret);

if (scope.isPresent()) {
requestBuilder.addFormParam("scope", scope.get());
}

return runRequestWithTokenResponse(requestBuilder, asyncHttpClient);
}

如果某个项目使用这个库,我将运行例如 1000 个请求,即使它们会完成,我最终会挂起很多线程。达到请求后我正在做的事情:

asyncHttpClient.close();

我可以定义一些要使用的线程池吗?

Typically, AHC will usually underperform if you create a new client for each request, as it will create new threads and connection pools for each

这就是我实际上正在做的事情..

最佳答案

当你初始化AsyncHttpClient对象时

你可以这样做,可以通过 AsyncHttpClientConfig 配置连接池行为:

AsyncHttpClient http = asyncHttpClient(config()
.setMaxConnections(500)
.setMaxConnectionsPerHost(200)
.setPooledConnectionIdleTimeout(100)
.setConnectionTtl(500)
);

关于Java asyncHttpClient 为每个连接创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52930597/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com