11

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.

sam
  • 123
  • 1
  • 1
  • 10
  • Are you planning to keep http connections open between calls? – jny Feb 03 '16 at 19:41
  • I am trying to understand what the default behavior is, how long the connection is available while it is inactive – sam Feb 03 '16 at 19:45

1 Answers1

9

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?

Community
  • 1
  • 1
jny
  • 7,739
  • 3
  • 30
  • 53
  • 2
    Thanks for the answer it helps me get going, one last question I am using the plain RestTemplate with SimpleClientHttpRequestFactory, basically the first request takes around 5 seconds in connecting to another REST Service via(RestTemplate), I see that java.net.UrlConnection.connect() is taking, but subsequent calls are fast. The delay happens again if the server is idle for a minute, IS this the default behavior? Does pooling connections eliminates that delay, when the server is idle? – sam Feb 04 '16 at 22:12
  • Usually it takes a lot less than 5 seconds to connect. There could be a network problem or the problem with the destination rest service. – jny Feb 05 '16 at 14:45
  • I was searching how to reuse a session cookie upon success logon and with HttpComponentsClientHttpRequestFactory it works great (no need to add the cookie for each new request) – Y.M. May 11 '16 at 08:37