Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default keep-alive time for a HttpConnection when using Spring Rest Template

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.

like image 666
sam Avatar asked Feb 03 '16 18:02

sam


People also ask

What is the default timeout for spring RestTemplate?

The default timeout is infinite. By default RestTemplate uses SimpleClientHttpRequestFactory and that in turn uses HttpURLConnection.

How do I set connection timeout for RestTemplate?

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.

How do you implement timeout in REST API?

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.


Video Answer


1 Answers

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?

like image 111
jny Avatar answered Sep 27 '22 18:09

jny