Spring RestTemplate - 需要释放连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40161117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:14:47  来源:igfitidea点击:

Spring RestTemplate - Need to release connection?

springhttpclientresttemplate

提问by Umar

This is my Configuration for Rest Template,

这是我的休息模板配置,

    @Bean
    @Qualifier("myRestService")
    public RestTemplate createRestTemplate(@Value("${connection.timeout}") String maxConn) {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
         connectionManager.setMaxTotal(maxTotalConn);
         connectionManager.setDefaultMaxPerRoute(maxPerChannel);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(100000).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();
        ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        RestTemplate restTemplate = new RestTemplate(factory);

        restTemplate.setErrorHandler(new RestResponseErrorHandler());
         restTemplate.setMessageConverters(createMessageConverters());

        return restTemplate;
    }

Am using PoolingHttpClientConnectionManager for managing the connections.

正在使用 PoolingHttpClientConnectionManager 来管理连接。

Its being accessed by the following code,

它被以下代码访问,

ResponseEntity<String> response = restClient.exchange( url, HttpMethod.GET, entity , String.class );

Do i need to release the connection after the above call or is it taken care by RestTemplate. If we need to take care of releasing connection.

我需要在上述调用后释放连接还是由 RestTemplate 处理。如果我们需要照顾释放连接。

Please can some one explain/show how to release the connection.

请有人解释/展示如何释放连接。

回答by Wilco Greven

You should declare the ClientHttpRequestFactory as a bean. By declaring it as a bean, it becomes managed by the Spring bean factory, which will call the factory's destroy method when the application is closed, or the bean goes out of scope. The destroy method of the ClientHttpRequestFactory will close the underlying ClientConnectionManager's connection pool. You can check the Spring API docs for this.

您应该将 ClientHttpRequestFactory 声明为 bean。通过将其声明为 bean,它由 Spring bean 工厂管理,当应用程序关闭或 bean 超出范围时,它将调用工厂的 destroy 方法。ClientHttpRequestFactory 的 destroy 方法将关闭底层 ClientConnectionManager 的连接池。您可以为此检查 Spring API 文档。

@Bean
public ClientHttpRequestFactory createRequestFactory(@Value("${connection.timeout}") String maxConn) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
     connectionManager.setMaxTotal(maxTotalConn);
     connectionManager.setDefaultMaxPerRoute(maxPerChannel);

    RequestConfig config = RequestConfig.custom().setConnectTimeout(100000).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(config).build();
    return new HttpComponentsClientHttpRequestFactory(httpClient);
}

Then you can use this bean to create your RestTemplate:

然后你可以使用这个 bean 来创建你的 RestTemplate:

@Bean
@Qualifier("myRestService")
public RestTemplate createRestTemplate(ClientHttpRequestFactory factory) {
    RestTemplate restTemplate = new RestTemplate(factory);

    restTemplate.setErrorHandler(new RestResponseErrorHandler());
    restTemplate.setMessageConverters(createMessageConverters());

    return restTemplate;
}

回答by Deepak Singhvi

The question which you have asked: Do i need to release the connection after the above call or is it taken care by RestTemplate. If we need to take care of releasing connection.

您提出的问题: 我是否需要在上述调用后释放连接,还是由 RestTemplate 处理。如果我们需要照顾释放连接。

No, you do not need to close the connection on the response, if you use resttemplate.

不,如果您使用 resttemplate,则不需要关闭响应上的连接。

From the apache httpclient, you need to consume the complete response (EntityUtils.consume(HttpEntity) and close the response.

从 apache httpclient,您需要使用完整的响应 (EntityUtils.consume(HttpEntity) 并关闭响应。

This can be verified in the ClientConnectionRelease.java

这可以在ClientConnectionRelease.java 中验证

But RestTemplate does this for you, to verify the same have a look into RestTemplate.java

但是 RestTemplate 为你做了这个,为了验证同样的,看看 RestTemplate.java

Look for method

寻找方法

protected <T> T doExecute(URI url,...) {
 try {
        ClientHttpRequest request = this.createRequest(url, method);
        ...
        response = request.execute();
        ...
        if(responseExtractor != null) {
            var7 = responseExtractor.extractData(response);
            return var7;
        }
       ...
       ...
    } finally {
        if(response != null) {
            response.close();
        }

    }
}

Where response extractor does the work for you by consuming the response using responseExtractor.extractData(response);

响应提取器通过使用responseExtractor.extractData(response)消耗响应来为您完成工作

And after extracting the data completely it is closing response.close()as well.

在完全提取数据后,它也在关闭response.close()