gpt4 book ai didi

httpclient - CloseableHttpClient : connection hangs forever

转载 作者:行者123 更新时间:2023-12-04 20:29:52 33 4
gpt4 key购买 nike

我对 CloseableHttpClient 管理的连接有问题。
Spring 服务管理 ny 连接:

@Service
public class MyService {
...
private CloseableHttpClient closeableHttpClient;

public String setPayment() {
...
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(ACCEPT, APP_JSON);
httpPost.setHeader(CONTENT_TYPE, APP_JSON);
StringEntity entity = new StringEntity(request, CHARSET);
httpPost.setEntity(entity);
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
logger.info("Execution");
} catch (IOException e) {
logger.error("Error");
}
}
}

当执行不成功时,我的 setPayment 方法最多被调用 3 次。有时在第一次执行后我的方法挂起没有响应。
欢迎任何建议。

最佳答案

我建议您执行以下操作:

1)在构造函数中设置超时:

public MyService() {
int timeout = 180;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * 1000)
.setConnectionRequestTimeout(timeout * 1000)
.setSocketTimeout(timeout * 1000).build();
closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}

2)使用try-with-resources来管理CloseableHttpResponse
    public String setPayment() {
...

HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(ACCEPT, APP_JSON);
httpPost.setHeader(CONTENT_TYPE, APP_JSON);
StringEntity entity = new StringEntity(request, CHARSET);
httpPost.setEntity(entity);
try (CloseableHttpResponse response = closeableHttpClient.execute(httpPost)){
logger.info("Execution");
} catch (IOException e) {
logger.error("Error");
}
}

关于httpclient - CloseableHttpClient : connection hangs forever,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785108/

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