VOOZH about

URL: https://dzone.com/articles/timeout-in-spring-boot-with-restclient-webclient-a

⇱ Spring Boot Timeout Handling Strategies


Related

  1. DZone
  2. Coding
  3. Java
  4. Spring Boot Timeout Handling With RestClient, WebClient, and RestTemplate

Spring Boot Timeout Handling With RestClient, WebClient, and RestTemplate

Explore how to implement timeouts using three popular approaches: RestClient, RestTemplate, and WebClient, all essential components in Spring Boot.

By Apr. 30, 24 · Tutorial
Likes
Comment
Save
28.0K Views

Join the DZone community and get the full member experience.

Join For Free

In modern web applications, integrating with external services is a common requirement. However, when interacting with these services, it's crucial to handle scenarios where responses might be delayed or fail to arrive. Spring Boot, with its extensive ecosystem, offers robust solutions to address such challenges. 

In this article, we'll explore how to implement timeouts using three popular approaches: RestClient, RestTemplate, and WebClient, all essential components in Spring Boot.

1. Timeout With RestTemplate

First, let's demonstrate setting a timeout using RestTemplate, a synchronous HTTP client.

Java
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

public class RestTemplateExample {

public static void main(String[] args) {
 
 var restTemplate = new RestTemplate();
 
 var url = "https://api.example.com/data";
 var timeout = 5000; // Timeout in milliseconds

 restTemplate.getForEntity(url, String.class);
 
 System.out.println(response.getBody());
 }
}


In this snippet, we're performing a GET request to `https://api.example.com/data`. However, we haven't set any timeout, which means the request might hang indefinitely in case of network issues or server unavailability.

To set a timeout, we need to configure RestTemplate with an appropriate `ClientHttpRequestFactory`, such as `HttpComponentsClientHttpRequestFactory`.

Java
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

public class RestTemplateTimeoutExample {

public static void main(String[] args) {

 var url = "https://api.example.com/data";
 var timeout = 5000; 

 var clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
 clientHttpRequestFactory.setConnectTimeout(timeout); 
 clientHttpRequestFactory.setConnectionRequestTimeout(timeout); 
 
 var restTemplate = new RestTemplate(clientHttpRequestFactory);
 
 restTemplate.getForEntity(url, String.class);
 
 System.out.println(response.getBody());
 }
}


2. Timeout With WebClient

WebClient is a non-blocking, reactive HTTP client introduced in Spring WebFlux. Let's see how we can use it with a timeout:

Java
import org.springframework.web.reactive.function.client.WebClient;
import java.time.Duration;

public class WebClientTimeoutExample {

public static void main(String[] args) {
 
 var client = WebClient.builder()
 .baseUrl("https://api.example.com")
 .build();

 client.get()
 .uri("/data")
 .retrieve()
 .bodyToMono(String.class)
 .timeout(Duration.ofMillis(5000))
 .subscribe(System.out::println);
 }
 
}


Here, we're using WebClient to make a GET request to `/data` endpoint. The `timeout` operator specifies a maximum duration for the request to wait for a response.

3. Timeout With RestClient

RestClient is a synchronous HTTP client that offers a modern, fluent API since Spring Boot 3.2. New Spring Boot applications should replace RestTemplate code with RestClient API.

Now, let's implement a RestClient with timeout using `HttpComponentsClientHttpRequestFactory`:

Java
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import java.time.Duration;

public class RestClientTimeoutExample {

public static void main(String[] args) {
 
 var factory = new HttpComponentsClientHttpRequestFactory();
 factory.setConnectTimeout(5000);
 factory.setReadTimeout(5000);
 
 var restClient = RestClient
 .builder()
 .requestFactory(clientHttpRequestFactory)
 .build();
 
 var response = restClient
 .get()
 .uri("https://api.example.com/data")
 .retrieve()
 .toEntity(String.class);
 
 System.out.println(response.getBody());
 }
}


In this code, we define a specified timeout using HttpComponentsClientHttpRequestFactory and use it in RestClient.builder().

By setting timeouts appropriately, we ensure that our application remains responsive even in scenarios where external services are slow or unresponsive.

This proactive approach enhances the overall reliability and resilience of our Spring Boot applications.

Conclusion

In summary, handling timeouts is important for web apps to stay responsive and robust during interactions with external services. We explored three popular Spring Boot approaches for implementing timeouts effectively: RestTemplate, WebClient, and RestClient. By setting appropriate timeouts, developers can ensure applications gracefully handle delayed or failed responses and enhance overall reliability and user experience in network conditions and service availability.

Java (programming language) resttemplate Spring Boot Timeout (computing)

Opinions expressed by DZone contributors are their own.

Related

  • How to Identify the Underlying Causes of Connection Timeout Errors for MongoDB With Java
  • A Spring Boot App With Half the Startup Time
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: