gpt4 book ai didi

java - HttpClient 连接池关闭

转载 作者:搜寻专家 更新时间:2023-11-01 03:46:42 25 4
gpt4 key购买 nike

我正在使用 HttpClient v4.5.5

我有一个 HttpClient 如下:

PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(totalMaxConnections);
connManager.setDefaultMaxPerRoute(defaultMaxConnPerRoute);
CloseableHttpClient httpClient =HttpClients.custom().setConnectionManager(connManager).setConnectionManagerShared(true).build();

然后我使用 http 客户端如下:

protected Response connect(final Function<AbstractHttpAdapter, CloseableHttpResponse> pcAction) {
Response response = null;
final Instant begin = Instant.now();
try {
final CloseableHttpResponse closableResp = pcAction.apply(this);
try {
final Instant end = Instant.now();
if (closableResp != null) {
final HttpEntity responseEntity = closableResp.getEntity();
if (responseEntity != null) {
response = new Response();
InputStream is = responseEntity.getContent();
try {

final ContentType contentType = ContentType.getOrDefault(responseEntity);
Charset charset = contentType.getCharset();
if (charset == null)
charset = Charset.forName("UTF-8");
response.responseText = IOUtils.toString(is, charset.toString());
if (closableResp.getStatusLine() != null) {
response.statusLine = closableResp.getStatusLine();

}
Map<String, String> responseHeaders = new HashMap<>();
Header[] headers = closableResp.getAllHeaders();
for (Header h : headers) {
responseHeaders.put(h.getName(), h.getValue());
}
response.responseHeaders = responseHeaders;
response.responseDuration = Duration.between(begin, end).toMillis();
} catch (UnsupportedOperationException | IOException e) {
LOGGER.error("IO Error: [{}]", e.getMessage());
LOGGER.debug("IO Error: {}", e);
return null;
} finally {
is.close();
}
}
} else {
LOGGER.debug("NULL CloseableHttpResponse!");
}
} finally {
if (closableResp != null)
closableResp.close();
}
} catch (IOException e) {
LOGGER.error("IO Error: [{}]", e.getMessage());
LOGGER.debug("IO Error: {}", e);
response = null;
} catch (Exception ex) {
LOGGER.error("IO Error: [{}]", ex.getMessage());
LOGGER.debug("IO Error: {}", ex);
response = null;
}
return response;
}

public CloseableHttpResponse executePost(final URL url, final String request, final int connectTimeout,
final int readTimeout, Map<String, String> extraHeaders) {

LOGGER.trace("Executing post request...");
CloseableHttpResponse closeableHttpResponse = null;
final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
final RequestConfig requestConfig = requestConfigBuilder.setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout).build();

final URI uri = prepareUri(url, null);
final HttpPost httpPost = new HttpPost(uri);
try {
httpPost.setEntity(new StringEntity(request, StandardCharsets.UTF_8));
httpPost.setConfig(requestConfig);
if (MapUtils.isNotEmpty(extraHeaders)) {
for (Map.Entry<String, String> header : extraHeaders.entrySet()) {
httpPost.setHeader(header.getKey(), header.getValue());
}
}
closeableHttpResponse = httpClient.execute(httpPost, HttpClientContext.create());
} catch (ClientProtocolException e) {
LOGGER.error("HTTP Error for URL [{}] and RequestParams [{}]: {}", url, request, e);
} catch (IOException e) {
LOGGER.error("IO Error for URL [{}] and RequestParams [{}]: {}", url, request, e.getMessage());
LOGGER.debug("IO Error for URL [{}] and RequestParams [{}]: {}", url, request, e);
} catch (Exception e) {
LOGGER.error("General Error for URL [{}] and RequestParams [{}]: {}", url, request, e);
}
return closeableHttpResponse;
}

定期(每隔几分钟)通过threadPoolTask​​Scheduler调用connect

偶尔会报错

java.lang.IllegalStateException: Connection pool shut down 从我读到的内容来看,这种情况要么发生在旧版 HttpClient 上,要么发生在您关闭 HttpClient 时。我不这样做。所以我不明白为什么会出现此错误。它恢复了,但是有这样的异常是一个问题。

最佳答案

同样的错误,但终于解决了。这个错误导致我使用 try () {} 如下:

try (PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager()) {
manager.setMaxTotal(600);
manager.setDefaultMaxPerRoute(100);

此构造将自动关闭资源。

class:PoolingHttpClientConnectionManager 存在如下方法:

 public void close() {
this.shutdown();
}

最后会调用 close()。

关于java - HttpClient 连接池关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48685815/

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