What Is @Retry in Spring?

Simply put

In Spring, @Retry is an annotation that allows you to specify that a method should be retried if it fails due to certain exceptions. This annotation is part of Spring's retry support, which provides a declarative way to handle transient failures by automatically retrying failed operations.

Here's how you can use @Retry in Spring:

  • Annotate the Method: You annotate the method you want to retry with @Retry.

  • Configure Retry Behavior: You can configure the behavior of the retry by specifying parameters such as the maximum number of retry attempts, the types of exceptions that trigger a retry, and the backoff strategy between retry attempts.

  • Enable Retry Configuration: You need to enable retry configuration in your Spring application context either through XML configuration or Java configuration.

Configuration

  • @EnableRetry: This annotation is used to enable Spring's support for retrying failed method invocations. By default, Spring's retry support is not enabled, so you need to annotate a configuration class with @EnableRetry to activate it. Setting proxyTargetClass to true indicates that the proxying mechanism should use class-based proxies instead of interface-based ones.

  • @Retryable: This annotation is used to indicate that a method should be retried if it fails. You can specify the types of exceptions that should trigger a retry, the maximum number of attempts, and the backoff strategy to be used between attempts. In your example, it retries for any exception (Exception.class), allows a maximum of 3 attempts (maxAttempts = 3), and uses a fixed backoff strategy with a delay of 2000 milliseconds between retries (backoff = @Backoff(2000)).

  • @Backoff: This annotation, used in conjunction with @Retryable, specifies the backoff strategy to use between retry attempts. In your example, it uses a fixed backoff strategy with a delay of 2000 milliseconds between retry attempts.

  • @Recover: This annotation is used in conjunction with @Retryable to specify a method that should be invoked if all retry attempts fail. The method annotated with @Recover should have a compatible signature with the retryable method and should be able to handle the same exceptions. When all retry attempts are exhausted, the @Recover-annotated method will be invoked to handle the failure.

Example

java 复制代码
@Service
public class RetryService {
	AtomicInteger COUNTER = new AtomicInteger(0);
    @Retryable(retryFor = Exception.class, maxAttempts = 3, backoff = @Backoff(2000),
                recover = "recover")
    public String calling3rdPartyAPI() throws Exception {
        COUNTER.incrementAndGet();
        if(COUNTER.get() == 1 || COUNTER.get() == 2 || COUNTER.get() == 3) {
            System.out.println("COUNTER = " + COUNTER);
            throw new Exception("Forcefully Exception ");
        }
        return "SUCCESS";
    }
    //this method will call after all attempt is getting over
     @Recover
     public String recover(Exception e) {
      System.out.println("Recover method called after all retry attempt and still getting error");
         return "Error Class :: " + e.getClass().getName();
     }
}

Notice that

Using @Retryable with idempotent methods is generally safe as long as the method's logic remains consistent across retries. Idempotent methods produce the same result regardless of how many times they are executed with the same inputs.


See

https://docs.spring.io/spring-batch/docs/4.1.x/reference/html/retry.html

https://medium.com/@vivekkadiyanits/retryable-a-retry-pattern-of-spring-boot-bf85290b8404

相关推荐
Minyy112 小时前
SpringBoot程序的创建以及特点,配置文件,LogBack记录日志,配置过滤器、拦截器、全局异常
xml·java·spring boot·后端·spring·mybatis·logback
ai大佬10 小时前
Java 开发玩转 MCP:从 Claude 自动化到 Spring AI Alibaba 生态整合
java·spring·自动化·api中转·apikey
来自星星的猫教授12 小时前
spring,spring boot, spring cloud三者区别
spring boot·spring·spring cloud
Bling_13 小时前
请求参数、路径参数、查询参数、Spring MVC/FeignClient请求相关注解梳理
java·spring·spring cloud·mvc
-曾牛13 小时前
企业级AI开发利器:Spring AI框架深度解析与实战
java·人工智能·python·spring·ai·rag·大模型应用
二进制独立开发14 小时前
[Trae 04.22+]适用于JAVA Spring开发的智能体提示词
spring·trae
大家都说我身材好15 小时前
Spring缓存注解深度实战:3大核心注解解锁高并发系统性能优化‌
spring·缓存·性能优化
都叫我大帅哥15 小时前
Spring AI中的ChatClient:从入门到精通,一篇搞定!
java·spring·ai编程
都叫我大帅哥15 小时前
《@SpringBootApplication:Spring Boot的"一键启动"按钮,还是程序员的"免死金牌"?》
java·后端·spring
-曾牛16 小时前
Spring AI 快速入门:从环境搭建到核心组件集成
java·人工智能·spring·ai·大模型·spring ai·开发环境搭建