使用背景
在有些特定場景,如和第三方對接。
我們調(diào)用接口時需要支持重試功能,第一次調(diào)用沒成功,我們需要等待x秒后再次調(diào)用。
通常會設(shè)置重試次數(shù),避免業(yè)務(wù)。
一般我們會這樣寫
public ApiResponse<Boolean> test() {
//模擬調(diào)用
System.out.println("開始調(diào)用,第" + num + "次");
//業(yè)務(wù)邏輯
boolean result = false;
if (result) {
System.out.println("執(zhí)行完成!");
} else if (num >= totalNum) {
System.out.println("重試結(jié)束");
num = 1;
} else {
System.out.println("重試");
++num;
test();
}
return ApiResponse.ok(true);
}
這樣寫本身,沒什么問題。
但是如果多個接口都需要重試的話,代碼就不優(yōu)雅了。
spring-retry介紹
spring系列的spring-retry是另一個實用程序模塊,
可以幫助我們以標(biāo)準(zhǔn)方式處理任何特定操作的重試。
在spring-retry中,所有配置都是基于簡單注釋的。
快速使用
加入依賴
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
開啟Retry
啟動上增加注解@EnableRetry文章來源:http://www.zghlxwxcb.cn/news/detail-481995.html
@EnableRetry
使用
@GetMapping("test")
@Retryable(value = Exception.class,maxAttempts = 5,backoff = @Backoff(delay = 2000,multiplier = 1.5))
public ApiResponse<Boolean> test() {
System.out.println("開始調(diào)用,第" + num + "次");
boolean result = false;
if (!result){
num++;
throw new BizException("調(diào)用失敗,需要重試");
}
System.out.println("執(zhí)行完成");
return ApiResponse.ok(true);
}
參數(shù)
value:拋出指定異常才會重試
include:和value一樣,默認為空,當(dāng)exclude也為空時,默認所有異常
exclude:指定不處理的異常
maxAttempts:最大重試次數(shù),默認5次
backoff:重試等待策略,默認使用@Backoff,@Backoff的value默認為1000L,我們設(shè)置為2000L;multiplier(指定延遲倍數(shù))默認為0,表示固定暫停1秒后進行重試,如果把multiplier設(shè)置為1.5,則第一次重試為2秒,第二次為3秒,第三次為4.5秒。文章來源地址http://www.zghlxwxcb.cn/news/detail-481995.html
到了這里,關(guān)于SpringBoot如何優(yōu)雅的實現(xiàn)重試功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!