When is destroy() method called in HttpComponentsClientHttpRequestFactory class?

Viewed 100

I have created CloseableHttpClient object as shown below. I am trying to understand when will the destroy method in HttpComponentsClientHttpRequestFactory class be called? I tried debugging by terminating the application but the destory() method is not called when the application is terminated.

CloseableHttpClient client = HttpClientBuilder.create().setSSLSocketFactory(csf).setDefaultRequestConfig(config).build();

return new HttpComponentsClientHttpRequestFactory(client);

1 Answers

You need to define HttpComponentsClientHttpRequestFactory 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 connection pool.

@Bean
public ClientHttpRequestFactory createRequestFactory() {
    CloseableHttpClient client = HttpClientBuilder.create().setSSLSocketFactory(csf).setDefaultRequestConfig(config).build();
    return new HttpComponentsClientHttpRequestFactory(client);
}

HttpComponentsClientHttpRequestFactory implements DisposableBean interface
See documentation or Destruction Callbacks:

Interface to be implemented by beans that want to release resources on destruction. A BeanFactory will invoke the destroy method on individual destruction of a scoped bean. An ApplicationContext is supposed to dispose all of its singletons on shutdown, driven by the application lifecycle.

Related