當我們調用接口的時候由於網絡原因可能失敗,再嘗試就成功了,這就是重試機制。非冪等的情況下要小心使用重試。
tips:冪等性
HTTP/1.1中對冪等性的定義是:一次和多次請求某一個資源對於資源本身應該具有同樣的結果(網絡超時等問題除外)。也就是說,其任意多次執行對資源本身所產生的影響均與一次執行的影響相同。
注解方式使用Spring Retry
(一)Maven依賴
<!-- 重試機制 -->
<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
@Configuration
public class RetryConfiguration {
}
(三)Service方法編寫
@Retryable注解:
value: 拋出指定異常才會重試
include:和value一樣,默認為空,當exclude也為空時,默認所以異常
exclude:指定不處理的異常
maxAttempts:最大重試次數,默認3次
backoff:重試等待策略,默認使用@Backoff,@Backoff的value默認為1000L;multiplier(指定延遲倍數)
@Recover注解:
當重試達到指定次數時候該注解的方法將被回調
發生的異常類型需要和@Recover注解的參數一致
@Retryable注解的方法不能有返回值,不然@Recover注解的方法無效
@Service
public 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("開始進行除法運算");
if (b == 0) {
throw new RuntimeException();
}
logger.info("{} / {} = {}", a, b, a / b);
}
@Recover
public void recover() {
logger.error("被除數不能為0");
}
}
(四)測試
@RunWith(SpringRunner.class)
@SpringBootTest
public 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不能在本類使用,不然不會生效。如果直接調用execute重試機制將不會生效,調用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("開始進行除法運算");
if (b == 0) {
throw new DevideException("被除數不能為0");
}
logger.info("{} / {} = {}", a, b, a / b);
}
使用@Retryable不能使用try catch捕獲異常為簡單
本文由博客一文多發平台 OpenWrite 發布!