Skip to main content

How to Retry Using Restclient

Spring-Boot Restclient
Author
Harpal Singh
Software Engineer
Table of Contents

1. Introduction

In this quick tutorial, we’ll learn how to implement retryable calls using RestClient with the support of spring-retry.

Sometimes, network connections can be unreliable, leading to temporary failures in making HTTP requests. There can be many reasons for these failures, so we must systematically handle them.

We know that WebClient provides an out-of-the-box retry mechanism. However, RestClient still needs this feature. Let’s see how to use spring-retry, a library that allows failed operations to be retried.

2. Setting up spring-retry

In short, spring-retry offers a simple approach to implementing retry capabilities through annotations. Additionally, we can customize the behavior as we wish. But first, we need to import the latest version of spring-retry and spring-aspects into our project:

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>2.0.5</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>6.1.4</version>
</dependency>

Now, we can use the @Retryable annotation. Let’s use it on a service method that encapsulates a RestClient call.

3. Configure RestClient with @Retryable

Finally, we can annotate a method with @Retryable to enable retry functionality. Additionally, we can also customize the retry behavior, for example, define a backoff policy:

@EnableRetry
public class ExampleService {
    @Retryable(maxAttempts = 5, backoff = @Backoff(delay = 1000))
    public String performRestCall() {
        return restClient
        .get()
        .uri("https://example.com")
        .retrieve()
        .body(String.class);
    }
}

Above, we use @EnableRetry to activate the retry policy and annotate the service method with @Retryable. This emulates a post call to an example URI and returns a String. We must annotate with @EnableRetry; otherwise, the @Retryable annotation will be ignored.

3.1. Retrying On Exceptions

In some cases, we may want to rerun a method when an exception is thrown. For this, we can use the retryFor attribute of @Retryable annotation. For example, we can retry a method call when a CustomException is thrown:

@Retryable(maxAttempts = 5, retryFor = {CustomException.class})
public String performRestCallWithCustomException() {
    // ...
    // throws CustomException
}

As we can see, we can easily customize the retry behavior as we want.

4. Conclusion

In this tutorial, we learned how to implement a retry mechanism using RestClient and spring-retry. We also saw how to use the @Retryable annotation to enable retry functionality and customize the retry behavior.

We can look for the complete code on Github.

Related

Running PostgreSQL in Docker Container
DevOps Postgres Docker Database
Cookie Policy for NamasteCode