How to set connection timeout for RestTemplate in spring? - CodeByAkram

How to set connection timeout for RestTemplate in spring?

How to set connection timeout for RestTemplate in spring? codebyakram

We can set the timeout for RestTemplate by doing some custom configuration for RestTemplate.

First you need to create a class named as HttpClientConfig in this class we configure HttpClient because RestTemplate internally uses the HttpClient.


package com.codebyakram;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfig {

 public static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(HttpClientConfig.class.getName());
 // Determines the timeout in milliseconds until a connection is established.
 private static final int CONNECT_TIMEOUT = 30000;

 // The timeout when requesting a connection from the connection manager.
 
 private int REQUEST_TIMEOUT = 10000;
 
 @Bean
 public CloseableHttpClient httpClient() {
  RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).build();
  return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
 }
}

Here in this class we setting HttpClient in RestTemplate

package com.codebyakram;

import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

 @Autowired
 CloseableHttpClient httpClient;


 @Bean
 public RestTemplate restTemplate() {
  RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
  return restTemplate;
 }

 @Bean
 public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
  HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
  clientHttpRequestFactory.setHttpClient(httpClient);
  return clientHttpRequestFactory;
 }

 @Bean
 public TaskScheduler taskScheduler() {
  ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
  scheduler.setThreadNamePrefix("poolScheduler");
  scheduler.setPoolSize(50);
  return scheduler;
 }
}

So now we are done with the cofiguration of request timeout for RestTemplate.

No comments:

Post a Comment