SpringBoot3應(yīng)用中集成和使用Spring Retry的實(shí)踐記錄
1. 簡(jiǎn)介
Spring Retry是Spring生態(tài)系統(tǒng)中的一個(gè)重要組件,它提供了自動(dòng)重試失敗操作的能力。在分布式系統(tǒng)中,由于網(wǎng)絡(luò)抖動(dòng)、服務(wù)暫時(shí)不可用等臨時(shí)性故障,重試機(jī)制顯得尤為重要。本文將詳細(xì)介紹如何在 SpringBoot 3 應(yīng)用中集成和使用 Spring Retry。
2. 環(huán)境準(zhǔn)備
首先在 SpringBoot 3 項(xiàng)目中添加必要的依賴(lài):
<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>在啟動(dòng)類(lèi)或配置類(lèi)上添加 @EnableRetry 注解以啟用重試功能:
@SpringBootApplication
@EnableRetry
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}3. 使用方式
3.1 注解方式 基礎(chǔ)使用
最簡(jiǎn)單的使用方式是通過(guò) @Retryable 注解:
@Service
public class UserService {
@Retryable
public void riskyOperation() {
// 可能失敗的操作
}
}自定義重試策略
可以通過(guò) @Retryable 注解的參數(shù)來(lái)自定義重試行為:
@Service
@Slf4j
public class EmailServiceImpl implements IEmailService {
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
/**
* 發(fā)送簡(jiǎn)單文本郵件
*
* @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);
}
}
}當(dāng)執(zhí)行發(fā)生指定異常,將會(huì)嘗試進(jìn)行重試,一旦達(dá)到最大嘗試次數(shù),但仍有異常發(fā)生,就會(huì)拋出 ExhaustedRetryException。重試最多可進(jìn)行三次,兩次重試之間的延遲時(shí)間默認(rèn)為一秒。
失敗恢復(fù)機(jī)制
使用 @Recover 注解定義重試失敗后的恢復(fù)方法:
/**
* 發(fā)送簡(jiǎn)單文本郵件
*
* @param to
* @param subject
* @param text
*/
@Override
@Retryable(retryFor = MailSendException.class, // 指定異常類(lèi)型
maxAttempts = 3, // 最大重試次數(shù)
backoff = @Backoff(delay = 1000) // 指定退避策略,例如延遲時(shí)間
)
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);
}重試和失敗恢復(fù)效果

注意事項(xiàng)
注意@Recover 失效的情況:
- @Recover 方法的參數(shù)類(lèi)型與實(shí)際異常不匹配;
- @Recover 方法的返回類(lèi)型與 @Retryable 方法不一致;
- @Recover 方法的其他參數(shù)與 @Retryable 方法參數(shù)不匹配。
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è)務(wù)邏輯
return null;
});
}
}3.3 監(jiān)聽(tīng)重試過(guò)程
通過(guò)實(shí)現(xiàn)RetryListener接口,可以監(jiān)聽(tīng)重試的整個(gè)生命周期:
public class CustomRetryListener extends RetryListenerSupport {
@Override
public <T, E extends Throwable> void onError(RetryContext context,
RetryCallback<T, E> callback, Throwable throwable) {
// 記錄錯(cuò)誤日志
log.error("Retry error occurred", throwable);
}
@Override
public <T, E extends Throwable> void close(RetryContext context,
RetryCallback<T, E> callback, Throwable throwable) {
// 重試結(jié)束時(shí)的處理
log.info("Retry completed");
}
}將監(jiān)聽(tīng)器注冊(cè)到RetryTemplate:
@Configuration
public class RetryConfig {
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate template = new RetryTemplate();
// ... 其他配置 ...
template.registerListener(new CustomRetryListener());
return template;
}
}監(jiān)聽(tīng)重試效果

4. 最佳實(shí)踐
- 明確重試場(chǎng)景:只對(duì)臨時(shí)性故障使用重試機(jī)制,對(duì)于業(yè)務(wù)錯(cuò)誤或永久性故障應(yīng)直接失敗。
- 設(shè)置合理的重試次數(shù):通常3-5次即可,過(guò)多的重試可能會(huì)加重系統(tǒng)負(fù)擔(dān)。
- 使用退避策略:建議使用指數(shù)退避策略(ExponentialBackOffPolicy),避免立即重試對(duì)系統(tǒng)造成沖擊。
- 添加監(jiān)控和日志:通過(guò)RetryListener記錄重試情況,便于問(wèn)題排查。
- 設(shè)置超時(shí)時(shí)間:避免重試過(guò)程持續(xù)時(shí)間過(guò)長(zhǎng)。
5. 總結(jié)
Spring Retry為Spring應(yīng)用提供了強(qiáng)大而靈活的重試機(jī)制,既可以通過(guò)注解優(yōu)雅地實(shí)現(xiàn)重試,也可以使用RetryTemplate進(jìn)行更細(xì)粒度的控制。在實(shí)際應(yīng)用中,合理使用重試機(jī)制可以提高系統(tǒng)的健壯性和可用性。
需要注意的是,重試機(jī)制并非萬(wàn)能藥,在使用時(shí)要根據(jù)具體場(chǎng)景選擇合適的重試策略,并做好監(jiān)控和告警,以便及時(shí)發(fā)現(xiàn)和處理問(wèn)題。
到此這篇關(guān)于SpringBoot3應(yīng)用中集成和使用Spring Retry的實(shí)踐記錄的文章就介紹到這了,更多相關(guān)SpringBoot3 Spring Retry內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用spring retry重試機(jī)制的操作詳解
- SpringBoot @Retryable注解使用
- SpringBoot中使用spring-retry 解決失敗重試調(diào)用
- SpringBoot利用@Retryable注解實(shí)現(xiàn)接口重試
- springboot整合@Retryable實(shí)現(xiàn)重試功能的示例代碼
- Springboot Retry組件@Recover失效問(wèn)題解決方法
- SpringBoot整合spring-retry實(shí)現(xiàn)接口請(qǐng)求重試機(jī)制及注意事項(xiàng)
- SpringBoot @Retryable注解方式
相關(guān)文章
MyBatisPlus用JavaBean映射數(shù)據(jù)庫(kù)表及樂(lè)觀鎖實(shí)戰(zhàn)指南
本文主要介紹了MyBatis-Plus查詢(xún)中映射匹配兼容性相關(guān)概念,以及當(dāng)表字段與編碼屬性設(shè)計(jì)不同步時(shí)的解決辦法和JavaBean在MyBatis-Plus中的作用;同時(shí)講述了主鍵id生成策略控制、多記錄操作、邏輯刪除以及樂(lè)觀鎖等操作的實(shí)現(xiàn)方式2026-04-04
Idea中添加Maven項(xiàng)目支持scala的詳細(xì)步驟
這篇文章主要介紹了Idea中添加Maven項(xiàng)目支持scala,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
解析Java的InputStream類(lèi)并借助其讀取ppt文件
這篇文章主要介紹了Java的InputStream類(lèi)并借助其讀取ppt文件,講到了InputStream類(lèi)中一些常用的方法的問(wèn)題,需要的朋友可以參考下2015-11-11
解決SpringBoot配置文件項(xiàng)目重啟出現(xiàn)亂碼的問(wèn)題
最近在創(chuàng)建了SpringBoot項(xiàng)目后往配置文件中寫(xiě)了相關(guān)的系統(tǒng)配置,并且在上面加了中文注釋?zhuān)窃谥貑㈨?xiàng)目或開(kāi)機(jī)重啟后遇到了注釋亂碼的情況,下面這篇文章主要給大家介紹一下如何解決SpringBoot配置文件項(xiàng)目重啟出現(xiàn)亂碼的問(wèn)題,需要的朋友可以參考下2023-06-06
java實(shí)現(xiàn)socket從服務(wù)器連續(xù)獲取消息的示例
這篇文章主要介紹了java實(shí)現(xiàn)socket從服務(wù)器連續(xù)獲取消息的示例,需要的朋友可以參考下2014-04-04
詳解SpringBoot如何自定義啟動(dòng)畫(huà)面
當(dāng)我們?cè)趩?dòng)SpringBoot項(xiàng)目時(shí)候會(huì)在控制臺(tái)上看到一些單調(diào)的圖案,有些朋友覺(jué)得這些圖案很單調(diào),那我們是否可以自定義啟動(dòng)畫(huà)面呢,接下來(lái)小編就給大家介紹一下SpringBoot是如何實(shí)現(xiàn)自定義啟動(dòng)畫(huà)面,感興趣的同學(xué)跟著小編一起來(lái)看看吧2023-07-07

