Springboot中如何使用springretry重試機(jī)制,針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
tips:冪等性
HTTP/1.1中對冪等性的定義是:一次和多次請求某一個(gè)資源對于資源本身應(yīng)該具有同樣的結(jié)果(網(wǎng)絡(luò)超時(shí)等問題除外)。也就是說,其任意多次執(zhí)行對資源本身所產(chǎn)生的影響均與一次執(zhí)行的影響相同。
注解方式使用Spring Retry
(一)Maven依賴
(二)配置類添加注解 @EnableRetry
@EnableRetry@Configurationpublic class RetryConfiguration {}
(三)Service方法編寫
@Retryable注解:
value: 拋出指定異常才會(huì)重試
include:和value一樣,默認(rèn)為空,當(dāng)exclude也為空時(shí),默認(rèn)所以異常
exclude:指定不處理的異常
maxAttempts:較大重試次數(shù),默認(rèn)3次
backoff:重試等待策略,默認(rèn)使用@Backoff,@Backoff的value默認(rèn)為1000L;multiplier(指定延遲倍數(shù))
@Recover注解:
當(dāng)重試達(dá)到指定次數(shù)時(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); }}
注意事項(xiàng)
@Retryable不能在本類使用,不然不會(huì)生效。如果直接調(diào)用execute重試機(jī)制將不會(huì)生效,調(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)知識(shí)。