Spring RestTemplate - Need to release connection?

前端 未结 3 1515
情深已故
情深已故 2021-02-05 20:44

This is my Configuration for Rest Template,

    @Bean
    @Qualifier(\"myRestService\")
    public RestTemplate createRestTemplate(@Value(\"${connection.timeout}         


        
3条回答
  •  迷失自我
    2021-02-05 21:21

    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.

    @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
    @Qualifier("myRestService")
    public RestTemplate createRestTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
    
        restTemplate.setErrorHandler(new RestResponseErrorHandler());
        restTemplate.setMessageConverters(createMessageConverters());
    
        return restTemplate;
    }
    

提交回复
热议问题