SoFunction
Updated on 2025-04-07

Spring uses @Retryable to implement automatic retry mechanism

introduction

In a microservice architecture, calls between services may fail due to temporary errors, such as network fluctuations, database connection timeouts, or third-party services unavailability. To improve system reliability and fault tolerance, we can use an automatic retry mechanism to deal with these temporary failures. Spring provides @Retryable annotation to facilitate this function.

In this article, we will introduce how to implement an automatic retry mechanism in Spring using @Retryable to help you easily deal with common service call failures.

1. What is @Retryable?

@Retryable is an annotation provided by Spring Retry, which allows us to automatically retry when the method execution fails. You can specify the number of retry times, the time between retry, and the type of exception that triggers retry.

With @Retryable, you can greatly simplify the exception handling logic and hand over the complexity of retry to Spring Retry for processing, avoiding the cumbersomeness of manually implementing the retry mechanism.

2. How to use @Retryable in Spring?

2.1 Add dependencies

First, make sure your project contains Spring Retry-related dependencies. If you are using Spring Boot, add the following dependencies:

<dependency>
    <groupId></groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Then enable the Spring Retry feature in the main or configuration class of Spring Boot:

@EnableRetry
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        (, args);
    }
}

@EnableRetry annotation enables the Spring Retry feature, which automatically provides a retry mechanism for methods marked as @Retryable.

2.2 Using @Retryable annotation

Use the @Retryable annotation on business methods that need to be retryed, specifying the conditions for triggering retry, such as exception type, maximum number of retries and retry intervals.

import ;
import ;
 
@Service
public class MyService {
 
    @Retryable(value = {}, maxAttempts = 3, backoff = @Backoff(delay = 1000))
    public void performTask() throws Exception {
        ("Attempting to perform task...");
        // Simulation business failure        if (() &gt; 0.5) {
            throw new Exception("Task failed");
        }
        ("Task completed successfully");
    }
}

In the above code:

  • value = {}: Specify which exceptions trigger retry. Here,ExceptionAn exception in its subclass will trigger a retry.
  • maxAttempts = 3: Maximum number of retries, including the first call. If the method throws an exception and the retry does not reach the maximum, Spring Retry continues to try.
  • backoff = @Backoff(delay = 1000): The delay time between each retry is 1000 milliseconds (1 second). This helps avoid excessive load from multiple retry in a short period of time.

2.3 Configuring the retry policy

Apart frommaxAttemptsandbackoff@RetryableThere are also some other options to flexibly configure the retry policy.

  • backoff: Specify the retry rollback policy, you can set:
    • delay: The interval between each retry (unit: milliseconds).
    • multiplier: The multiplier of exponential backoff.
    • maxDelay: Maximum delay time.

Example:

@Retryable(value = {}, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 5000))
public void performTask() throws Exception {
    // Execute business logic}

In this example, the first retry will be 1 second interval, the second retry will be 2 seconds, and the third retry will be 4 seconds, but not more than 5 seconds.

2.4 Recovery method

You can also define a recovery method that executes after the maximum number of retries is exhausted. The recovery method can be used to handle the final failure situation and avoid system crashes. The parameters of the recovery method should be consistent with the exception type of the retry method.

import ;
import ;
import ;
import ;
 
@Service
public class MyService {
 
    @Retryable(value = {}, maxAttempts = 3, backoff = @Backoff(delay = 1000))
    public void performTask() throws Exception {
        ("Attempting to perform task...");
        if (() > 0.5) {
            throw new Exception("Task failed");
        }
        ("Task completed successfully");
    }
 
    @Recover
    public void recover(Exception e) {
        ("Recovery from failure: " + ());
    }
}

In this example, ifperformTaskThe method still fails after trying 3 times.recoverThe method will be called and the failed exception is passed.

3. Typical application scenarios

  • Temporary network failure: For example, you may experience short-term network problems when calling a remote API or microservice. pass@RetryableNote: We can automatically retry when network problems are recovered to improve the reliability of the system.

  • Database connection timeout: When performing database operations, you may occasionally encounter the problem of connection timeout. By configuring a retry policy, you can try again after the database connection is restored.

  • Message queue consumption failed: When consuming messages, if a temporary failure occurs (such as message processing timeout, network out of touch, etc.), we can pass@RetryableImplement automatic retry until the processing is successful.

4. Things to note

  • The number of retry times should be configured reasonably: Too many retry times may lead to increased system pressure and even cause other problems. Be sure to set it up reasonably according to business needsmaxAttempts

  • Avoid frequent retry: If the retry interval is too short, it may cause excessive load on the system. Reasonable configurationbackoffParameters to avoid resource consumption caused by frequent retry.

  • Use of recovery methods: After the number of retrys is exhausted, using the recovery method can ensure that the program does not crash directly, and some cleaning or subsequent processing can be done.

5. Summary

Using the Spring @Retryable annotation can easily implement the automatic retry mechanism, helping us automatically recover when facing temporary failures, reducing the complexity of manual processing failures. By reasonably configuring the number of retry times, retry intervals and recovery methods, the fault tolerance and stability of the system can be effectively improved. Whether in scenarios such as network requests, database operations, or message queue consumption, @Retryable is a very useful tool.

The above is the detailed content of Spring using @Retryable to implement the automatic retry mechanism. For more information about Spring @Retryable automatic retry, please follow my other related articles!