I am calling REST API from Spring Boot Application using RestTemplate. The REST API which I am calling having avg execution time approx. 2 Sec. But When I am calling it from Java Spring Boot application Its taking 3 sec. I know this delay is due to Network Latency cost. Is there any way to minimize this Network Latency?
@Hritik Could you pls help on this?
Rest template by default creates new Http Connection every time and closes that connection. This adds extra overhead to create a new connection every time because of which time is consumed in handshake process when creating the new connection.
We can use Http Pooling which will re-use the already opened connection and will save the time and overhead.
We can add below configuration class for Http Polling and can inject the rest template while calling the api.
@Bean
public RestTemplate restTemplate() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(100); // Maximum total connections
connectionManager.setDefaultMaxPerRoute(20); // Maximum connections per route
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(factory);
}