Springboot中如何使用springretry重試機(jī)制,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
tips:冪等性
HTTP/1.1中對冪等性的定義是:一次和多次請求某一個資源對于資源本身應(yīng)該具有同樣的結(jié)果(網(wǎng)絡(luò)超時等問題除外)。也就是說,其任意多次執(zhí)行對資源本身所產(chǎn)生的影響均與一次執(zhí)行的影響相同。
注解方式使用Spring Retry
(一)Maven依賴
<!-- 重試機(jī)制 --><dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.2.4.RELEASE</version></dependency><dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version></dependency>
(二)配置類添加注解 @EnableRetry
@EnableRetry@Configurationpublic class RetryConfiguration {}
(三)Service方法編寫
@Retryable注解:
value: 拋出指定異常才會重試
include:和value一樣,默認(rèn)為空,當(dāng)exclude也為空時,默認(rèn)所以異常
exclude:指定不處理的異常
maxAttempts:較大重試次數(shù),默認(rèn)3次
backoff:重試等待策略,默認(rèn)使用@Backoff,@Backoff的value默認(rèn)為1000L;multiplier(指定延遲倍數(shù))
@Recover注解:
當(dāng)重試達(dá)到指定次數(shù)時候該注解的方法將被回調(diào)
發(fā)生的異常類型需要和@Recover注解的參數(shù)一致
@Retryable注解的方法不能有返回值,不然@Recover注解的方法無效
@Servicepublic class RetryService { private Logger logger = LoggerFactory.getLogger(RetryService.class); @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 2)) public void devide(double a, double b){ logger.info("開始進(jìn)行除法運(yùn)算"); if (b == 0) { throw new RuntimeException(); } logger.info("{} / {} = {}", a, b, a / b); } @Recover public void recover() { logger.error("被除數(shù)不能為0"); }}
(四)測試
@RunWith(SpringRunner.class)@SpringBootTestpublic class BootdemoApplicationTests { @Autowired private RetryService retryService; private Logger logger = LoggerFactory.getLogger(BootdemoApplication.class); @Test public void retryTest() { //int count = retryService.retry(-1); retryService.retry(-1); //logger.info("庫存為:" + count); }}
注意事項
@Retryable不能在本類使用,不然不會生效。如果直接調(diào)用execute重試機(jī)制將不會生效,調(diào)用devide則重試生效。
public void execute(double a, double b) throws DevideException { devide(a, b); } @Retryable(value = DevideException.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 2)) public void devide(double a, double b) throws DevideException { logger.info("開始進(jìn)行除法運(yùn)算"); if (b == 0) { throw new DevideException("被除數(shù)不能為0"); } logger.info("{} / {} = {}", a, b, a / b); }
使用@Retryable不能使用try catch捕獲異常為簡單
關(guān)于Springboot中如何使用springretry重試機(jī)制問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。
分享名稱:Springboot中如何使用springretry重試機(jī)制-創(chuàng)新互聯(lián)
當(dāng)前路徑:http://www.chinadenli.net/article8/ijiop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設(shè)計公司、用戶體驗、自適應(yīng)網(wǎng)站、域名注冊、搜索引擎優(yōu)化、網(wǎng)站設(shè)計公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容