我有一个由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/