CloseableHttpClient:连接永远挂起

时间:2018-02-14 10:40:05

标签: httpclient

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

 ['hello', ['foo', 'test'], ['world', 'bar', 'idk'], 'am']

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

1 个答案:

答案 0 :(得分:2)

我建议你做以下事情:

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");
            }
        }
相关问题