DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Identify the Underlying Causes of Connection Timeout Errors for MongoDB With Java
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets

Trending

  • Your AI Agent Tests Are Passing, But Your Agent Is Still Broken
  • Building a DevOps-Ready Internal Developer Platform: A Hands-On Guide to Golden Paths, Self-Service, and Automated Delivery Pipelines
  • Feature Flag Debt: Performance Impact in Enterprise Applications
  • LLM-Powered Deep Parsing for Industrial Inventory Search
  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 
Fernando Boaglio user avatar
Fernando Boaglio
·
Apr. 30, 24 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
27.9K 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
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook