SpringBoot RestTemplate连接池:管理过时连接

时间:2018-03-15 05:41:42

标签: spring spring-boot resttemplate

我正在使用RestTemplate与ConnectionPooling一起使用PoolingHttpClientConnectionManager,如下面的代码所示:

PoolingHttpClientConnectionManager connectionManager = new 
PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);

connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    connectionManager.setMaxPerRoute(new HttpRoute(new 
HttpHost(excConfig.getImsServerEndpoint())), IMS_ROUTE_MAX_CONNECTIONS);

    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connectionManager).build();

    HttpComponentsClientHttpRequestFactory httpReqFactory = new HttpComponentsClientHttpRequestFactory(httpclient);
    httpReqFactory.setReadTimeout(DEFAULT_HTTP_TIMEOUT_MILLISECONDS);
    httpReqFactory.setConnectionRequestTimeout(DEFAULT_HTTP_TIMEOUT_MILLISECONDS);
    httpReqFactory.setConnectTimeout(DEFAULT_HTTP_TIMEOUT_MILLISECONDS);

    restTemplate = new RestTemplate(httpReqFactory);

RestTemplate是否负责自行终止Stale Connections,或者我是否需要对其进行一些特定的处理。

1 个答案:

答案 0 :(得分:1)

setStaleConnectionCheckEnabled已过时。

HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom()。 setStaleConnectionCheckEnabled(true)) .setConnectionManager(connectionManager) .build();

在HttpClient 4.5.3中,以下代码有效-

PoolingHttpClientConnectionManager connManager 
          = new PoolingHttpClientConnectionManager();
        connManager.setValidateAfterInactivity(20);

        HttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();