Master Spring Retry: Simplify Retry Logic in Spring Boot Applications
Learn how to use Spring Retry’s @Retryable and @Recover annotations to implement elegant, non-intrusive retry mechanisms in Spring Boot, covering configuration, code examples, parameter meanings, backoff strategies, and important considerations for reliable error handling.
Introduction
In real‑world projects, retrying failed operations is a common scenario, such as message sending failures, remote service invocation failures, or lock acquisition failures caused by network fluctuations. A simple try/catch or while loop can work but leads to scattered, intrusive code.
The spring-retry module provides annotation‑driven, non‑intrusive retry support that integrates cleanly with Spring Boot.
What is @Retryable?
spring-retryoffers a utility module that standardizes retry handling for any operation. All configurations are expressed via simple annotations.
Usage Steps
POM Dependency
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>Enable @Retryable
@EnableRetry
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}Add @Retryable to a Method
import com.mail.elegant.service.TestRetryService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalTime;
@Service
public class TestRetryServiceImpl implements TestRetryService {
@Override
@Retryable(value = Exception.class, maxAttempts = 3,
backoff = @Backoff(delay = 2000, multiplier = 1.5))
public int test(int code) throws Exception {
System.out.println("test被调用,时间:" + LocalTime.now());
if (code == 0) {
throw new Exception("情况不对头!");
}
System.out.println("test被调用,情况对头了!");
return 200;
}
}The annotation parameters have the following meanings: value: the exception types that trigger a retry. include: same as value, default empty; when both include and exclude are empty, all exceptions are retried. exclude: exception types that should not be retried. maxAttempts: maximum number of retry attempts (default 3). backoff: retry waiting strategy, typically using @Backoff. The default value is 1000 ms; in the example it is set to 2000 ms with a multiplier of 1.5, resulting in delays of 2 s, 3 s, and 4.5 s for successive attempts.
When Retries Are Exhausted
If all retry attempts fail, RetryOperations can delegate to a RecoveryCallback. Spring‑Retry also provides the @Recover annotation to define a fallback method that runs after a failed retry.
@Recover
@Recover
public int recover(Exception e, int code) {
System.out.println("回调方法执行!!!!");
// log to database or invoke other logic
return 400;
}The first parameter of the recovery method must be a Throwable (usually the same exception type configured in @Retryable). The method must reside in the same class as the retryable method, and its return type must match the retryable method’s return type.
Precautions
Because retry is implemented via AOP, self‑invocation within the same class is not intercepted.
If a recovery method is needed, the retryable method should return void when you want the recovery method to handle the result.
Do not use try/catch inside the retryable method; let exceptions propagate.
The recovery method’s parameters must include the exception type and any additional arguments required for handling.
Conclusion
This article introduced the usage of Spring Boot’s @Retryable annotation, its typical scenarios, configuration parameters, and important considerations, demonstrating how to add robust retry capabilities to your applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
