Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 38 章 Spring boot with Retryable

目录

38.1. @EnableResilientMethods
38.1.1. @ConcurrencyLimit 限流
38.1.2. @Retryable 重试
38.2. spring-retry
38.2.1. spring-retry 依赖
38.2.2. @EnableRetry 启用重试
38.2.3.
38.2.4. 高级用法

Springboot 实现重试有两个方案,一个是 Springboot 4.0 自带的 Retryable 是 Resilient 实现。另一个方案是 spring-retry 需要额外引入依赖。

38.1. @EnableResilientMethods

启用配置,在配置类上添加@EnableResilientMethods注解

		
		
		
		

38.1.1. @ConcurrencyLimit 限流

在需要限制并发的方法上添加@ConcurrencyLimit注解

		
@Configuration
@EnableResilientMethods
public class ResilientMethodsConfig {
    // 配置类
}

@Component
public class NotificationService {
    @ConcurrencyLimit(10)
    public void sendNotification() {
        this.jmsClient.destination("notifications").send(...);
    }
    
    @ConcurrencyLimit(1)
    public void processCriticalTask() {
        // 关键任务处理
    }
}		
		
			

38.1.2. @Retryable 重试

			
@Retryable
public void sendNotification() {
    this.jmsClient.destination("notifications").send(...);
}			
			
			

可通过@Retryable注解中的includes、excludes和implicit值属性,限制触发重试的异常类型。

			
@Retryable(  includes = MessageDeliveryException.class,  maxAttempts = 5,  delay = 100,  jitter = 10,  multiplier = 2,  maxDelay = 1000)
public void sendNotification() {    
	this.jmsClient.destination("notifications").send(...);
}			
			
			

RetryTemplate

			
var retryPolicy = RetryPolicy.builder()
        .includes(MessageDeliveryException.class)
        .maxAttempts(5)
        .delay(Duration.ofMillis(100))
        .build();
var retryTemplate = new RetryTemplate(retryPolicy);
retryTemplate.execute(() -> jmsClient.destination("notifications").send(...));