【问题标题】:CloseableHttpClient: connection hangs foreverCloseableHttpClient:连接永远挂起
【发布时间】:2018-02-14 10:40:04
【问题描述】:

我遇到了由 CloseableHttpClient 管理的连接问题。 Spring 服务管理任何连接:

@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 次。有时在第一次执行后,我的方法挂起而没有响应。 欢迎提出任何建议。

【问题讨论】:

    标签: httpclient


    【解决方案1】:

    我建议您执行以下操作:

    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");
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 2021-08-29
      相关资源
      最近更新 更多