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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Leverage Amazon BedRock Chat Model With Java and Spring AI
  • Using Spring AI to Generate Images With OpenAI's DALL-E 3
  • Implementing Row-Level Security

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  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 (2)
Comment
Save
Tweet
Share
19.7K 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

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Leverage Amazon BedRock Chat Model With Java and Spring AI
  • Using Spring AI to Generate Images With OpenAI's DALL-E 3
  • Implementing Row-Level Security

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!