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
Newsletter
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
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • A Spring Boot App With Half the Startup Time

Trending

  • Introducing senro: A Pipeline Engine You Program in Go
  • Kubernetes Rolling Updates Are Lying to You — and Your Users Are Paying for It
  • Ingesting Public Data That Fails Silently: Patterns From a TypeScript and Cloudflare Workers Pipeline
  • Designing for Hot Keys: When Distributed Systems Stop Distributing

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Apr. 30, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
28.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • A Spring Boot App With Half the Startup Time

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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