应用中有些和本地资源交付,或者和远程资源交付场景,如果此时失败了,你能确定失败的原因不是逻辑错误,此时你就可以重试。并不是所有失败场景都需要重试,比如你的应用中出现一个主键冲突的错误,此时你就完全没有必要针对这种错误进行重试。
固定次数重试
public void funWithRetry() {
int retryCount = 3;
for (int i = 0; i < retryCount; ++i) {
try {
fun();
break;
} catch (Exception e) {
log.warn("funWithRetry exception, retry i={}", i);
}
}
}
固定次数重试加延时
public void funWithRetry(final int retryCount, final int delaySecond) {
for (int i = 0; i < retryCount; ++i) {
try {
fun();
break;
} catch (Exception e) {
AsyncUtil.safeSleep(delaySecond * 1000L);
log.warn("funWithRetry exception, retry i={}", i);
}
}
}
使用resilience4j-retry进行重试