I am trying to know how long a HttpConnection is kept alive when inactive, before a new connection is created via Spring rest Template. I looked at default Connection Time-Out and Read Time-Out parameters, but I believe these are used in the context of connection time out when the connection is not established due to some failure etc.
What I am looking for is, how long a connection is kept alive if there is no activity (or) inactive, and how to configure this via Spring Rest Template (or) the underlying mechanism.
The default timeout is infinite. By default RestTemplate uses SimpleClientHttpRequestFactory and that in turn uses HttpURLConnection.
RestTemplate default timeoutprivate int connectTimeout = - 1 ; private int readTimeout = - 1 ; By default, resttemplate uses timeout property from JDK installed on the machine which is always infinite in not overridden. To override the default JVM timeout, we can pass these properties during JVM start.
One way we can implement a request timeout on database calls is to take advantage of Spring's @Transactional annotation. It has a timeout property that we can set. The default value for this property is -1, which is equivalent to not having any timeout at all.
By default RestTemplate
uses SimpleClientHttpRequestFactory
which in turn opens Java's HttpURLConnection
which by default supports keep-alive under certain conditions. If you want more control over how connections are handled, you can create restTemplate with HttpComponentsClientHttpRequestFactory
, which uses Apache HttpClient
library, e.g:
@Bean
RestTemplate restTemplate(SimpleClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
You can also see some discussions here:
How to Reuse HttpUrlConnection?
Persistent HttpURLConnection in Java
How to use RestTemplate efficiently in Multithreaded environment?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With