SpringBoot3應用中集成和使用Spring Retry的實踐記錄
1. 簡介
Spring Retry是Spring生態(tài)系統(tǒng)中的一個重要組件,它提供了自動重試失敗操作的能力。在分布式系統(tǒng)中,由于網絡抖動、服務暫時不可用等臨時性故障,重試機制顯得尤為重要。本文將詳細介紹如何在 SpringBoot 3 應用中集成和使用 Spring Retry。
2. 環(huán)境準備
首先在 SpringBoot 3 項目中添加必要的依賴:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>6.1.13</version>
</dependency>在啟動類或配置類上添加 @EnableRetry 注解以啟用重試功能:
@SpringBootApplication
@EnableRetry
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}3. 使用方式
3.1 注解方式 基礎使用
最簡單的使用方式是通過 @Retryable 注解:
@Service
public class UserService {
@Retryable
public void riskyOperation() {
// 可能失敗的操作
}
}自定義重試策略
可以通過 @Retryable 注解的參數來自定義重試行為:
@Service
@Slf4j
public class EmailServiceImpl implements IEmailService {
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
/**
* 發(fā)送簡單文本郵件
*
* @param to
* @param subject
* @param text
*/
@Override
@Retryable(retryFor = MailSendException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
public void sendSimpleEmail(String to, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
log.info("Simple email sent successfully to: {}", to);
} catch (Exception e) {
log.error("Failed to send simple email", e);
throw new MailSendException("Failed to send email", e);
}
}
}當執(zhí)行發(fā)生指定異常,將會嘗試進行重試,一旦達到最大嘗試次數,但仍有異常發(fā)生,就會拋出 ExhaustedRetryException。重試最多可進行三次,兩次重試之間的延遲時間默認為一秒。
失敗恢復機制
使用 @Recover 注解定義重試失敗后的恢復方法:
/**
* 發(fā)送簡單文本郵件
*
* @param to
* @param subject
* @param text
*/
@Override
@Retryable(retryFor = MailSendException.class, // 指定異常類型
maxAttempts = 3, // 最大重試次數
backoff = @Backoff(delay = 1000) // 指定退避策略,例如延遲時間
)
public void sendSimpleEmail(String to, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
log.info("Simple email sent successfully to: {}", to);
} catch (Exception e) {
log.error("Failed to send simple email", e.getMessage());
throw new MailSendException("Failed to send email", e);
}
}
@Recover
public void recover(MailSendException e, String param) {
// 處理最終失敗的情況
log.error("Final recovery : {}", param);
}重試和失敗恢復效果

注意事項
注意@Recover 失效的情況:
- @Recover 方法的參數類型與實際異常不匹配;
- @Recover 方法的返回類型與 @Retryable 方法不一致;
- @Recover 方法的其他參數與 @Retryable 方法參數不匹配。
3.2 編程式使用
除了注解方式,Spring Retry 還提供了 RetryTemplate 用于編程式重試:
@Configuration
public class RetryConfig {
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate template = new RetryTemplate();
// 配置重試策略
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(3);
// 配置退避策略
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(1000L);
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
}使用RetryTemplate:
@Service
public class UserService {
@Autowired
private RetryTemplate retryTemplate;
public void executeWithRetry() {
retryTemplate.execute(context -> {
// 需要重試的業(yè)務邏輯
return null;
});
}
}3.3 監(jiān)聽重試過程
通過實現(xiàn)RetryListener接口,可以監(jiān)聽重試的整個生命周期:
public class CustomRetryListener extends RetryListenerSupport {
@Override
public <T, E extends Throwable> void onError(RetryContext context,
RetryCallback<T, E> callback, Throwable throwable) {
// 記錄錯誤日志
log.error("Retry error occurred", throwable);
}
@Override
public <T, E extends Throwable> void close(RetryContext context,
RetryCallback<T, E> callback, Throwable throwable) {
// 重試結束時的處理
log.info("Retry completed");
}
}將監(jiān)聽器注冊到RetryTemplate:
@Configuration
public class RetryConfig {
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate template = new RetryTemplate();
// ... 其他配置 ...
template.registerListener(new CustomRetryListener());
return template;
}
}監(jiān)聽重試效果

4. 最佳實踐
- 明確重試場景:只對臨時性故障使用重試機制,對于業(yè)務錯誤或永久性故障應直接失敗。
- 設置合理的重試次數:通常3-5次即可,過多的重試可能會加重系統(tǒng)負擔。
- 使用退避策略:建議使用指數退避策略(ExponentialBackOffPolicy),避免立即重試對系統(tǒng)造成沖擊。
- 添加監(jiān)控和日志:通過RetryListener記錄重試情況,便于問題排查。
- 設置超時時間:避免重試過程持續(xù)時間過長。
5. 總結
Spring Retry為Spring應用提供了強大而靈活的重試機制,既可以通過注解優(yōu)雅地實現(xiàn)重試,也可以使用RetryTemplate進行更細粒度的控制。在實際應用中,合理使用重試機制可以提高系統(tǒng)的健壯性和可用性。
需要注意的是,重試機制并非萬能藥,在使用時要根據具體場景選擇合適的重試策略,并做好監(jiān)控和告警,以便及時發(fā)現(xiàn)和處理問題。
到此這篇關于SpringBoot3應用中集成和使用Spring Retry的實踐記錄的文章就介紹到這了,更多相關SpringBoot3 Spring Retry內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MyBatisPlus用JavaBean映射數據庫表及樂觀鎖實戰(zhàn)指南
本文主要介紹了MyBatis-Plus查詢中映射匹配兼容性相關概念,以及當表字段與編碼屬性設計不同步時的解決辦法和JavaBean在MyBatis-Plus中的作用;同時講述了主鍵id生成策略控制、多記錄操作、邏輯刪除以及樂觀鎖等操作的實現(xiàn)方式2026-04-04
解析Java的InputStream類并借助其讀取ppt文件
這篇文章主要介紹了Java的InputStream類并借助其讀取ppt文件,講到了InputStream類中一些常用的方法的問題,需要的朋友可以參考下2015-11-11
解決SpringBoot配置文件項目重啟出現(xiàn)亂碼的問題
最近在創(chuàng)建了SpringBoot項目后往配置文件中寫了相關的系統(tǒng)配置,并且在上面加了中文注釋,但是在重啟項目或開機重啟后遇到了注釋亂碼的情況,下面這篇文章主要給大家介紹一下如何解決SpringBoot配置文件項目重啟出現(xiàn)亂碼的問題,需要的朋友可以參考下2023-06-06
java實現(xiàn)socket從服務器連續(xù)獲取消息的示例
這篇文章主要介紹了java實現(xiàn)socket從服務器連續(xù)獲取消息的示例,需要的朋友可以參考下2014-04-04

