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

相关推荐
华科易迅4 小时前
Spring 事务(注解)
java·数据库·spring
希望永不加班6 小时前
SpringBoot 过滤器(Filter)与请求链路梳理
java·spring boot·后端·spring
恼书:-(空寄6 小时前
Spring 事务失效的 8 大场景 + 原因 + 解决方案
java·后端·spring
爱丽_8 小时前
Spring 事务:传播行为、失效场景、回滚规则与最佳实践
java·后端·spring
Zaki_gd10 小时前
Cortex-M7 D-Cache 与 DMA 缓存一致性说明
java·spring·缓存
Arthas21711 小时前
Java大厂面试:从Spring到微服务的全面技术考察
java·jvm·spring·微服务·面试·并发
烛之武11 小时前
SpringCloud基础(上)
笔记·spring·spring cloud
回到原点的码农12 小时前
maven导入spring框架
数据库·spring·maven
Predestination王瀞潞13 小时前
Java EE3-我独自整合(第一章:Spring入门)
java·spring·java-ee
bjzhang7513 小时前
SpringCloud——国产化改造,项目对接 TongWeb 嵌入版
后端·spring·spring cloud