spring-retry注解调用原理

Retry
github spring-retry

Introduction

spring-retry的官方说明:

Retry and backoff policies of retryable operations.
To make processing more robust and less prone to failure, it sometimes helps to automatically retry a failed operation in case it might succeed on a subsequent attempt. Errors that are susceptible to intermittent failure are often transient in nature.

spring-retry原先是spring-batch的一部分,后来单独成为一个项目了。
该项目maven坐标如下:

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>

spring-retry的两种使用方式:

  • 基于注解:spring-retry利用spring-aop对注解了特定注解的方法做代理拦截实现重试机制,重试过程中包含了重试、退避、断路器、恢复等操作,分别对应了注解:@Retryable @Backoff @CurcuitBreaker @Recover
  • 编码调用:使用RetryTemplate执行

案例

注解方式

@Configuration
@EnableRetry
public class Application {
    
    

}

@Service
class Service {
    
    
    @Retryable(RemoteAccessException.class)
    public void service() {
    
    
        // ... do something
    }
    @Recover
    public void recover(RemoteAccessException e) {
    
    
       // ... panic
    }
}

调用service方法如果抛出RemoteAccessException则默认重试执行3次,之后再去执行recover方法。同时@Retryable可以设置异常类型、重试次数、退避策略。

RetryTemplate方式

RetryTemplate template = RetryTemplate.builder()
				.maxAttempts(3)
				.fixedBackoff(1000)
				.retryOn(RemoteAccessException.class)
				.build();

template.execute(ctx -> {
    
    
    // ... do something
});

实现原理

注解调用原理

基于注解方式调用整体实现方式如下图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41866717/article/details/129895416