java失败重试
public class TryCatchReturnTry {
private static int retrySleepMillis = 1000; // 第一次睡眠时间
private static int maxRetryTimes = 5; // 最大重试次数
public static void main(String[] args) throws Exception {
int retryTimes = 0;
do {
try {
String result = execute(retryTimes);
if ("success".equals(result)) {
break;
}
} catch (Exception e) {
if (retryTimes + 1 > maxRetryTimes) {
System.out.println("重试达到最大次数【" + maxRetryTimes + "】");
System.out.println(e.getMessage());
throw new Exception("请求退出,超出重试次数");
}
String eMessage = e.getMessage();
// 系统错误, 1000ms后重试
if (eMessage.equals("/ by zero")) {
int sleepMillis = retrySleepMillis * (1 << retryTimes);
System.out.println("系统错误 " + eMessage + ",暂停时间:" + sleepMillis + "\n");
try {
System.out.println("【" + sleepMillis + "】 ms 后第【" + (retryTimes + 1) + "】次重试");
Thread.sleep(sleepMillis);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
} else {
throw e;
}
}
} while (retryTimes++ <= maxRetryTimes);
}
public static String execute(int retryTimes) {
System.out.print(DateUtil.now() + " 执行,结果:");
// =========模拟重试第3次成功后退出================================
// if ((retryTimes + 1) != 3) {
// int b = 1 / 0;
// }
// System.out.println("第" + (retryTimes + 1) + "次业务正常执行...");
// return "success";
// =========模拟重试第3次成功后退出================================
// =========模拟重试一直失败到达最大重试次数后退出================================
int b = 1 / 0;
return "fail";
// =========模拟重试第3次成功后退出================================
}
}
重试3次成功然后正常退出
2023-02-07 10:49:41 执行,结果:系统错误 / by zero,暂停时间:1000
【1000】 ms 后第【1】次重试
2023-02-07 10:49:42 执行,结果:系统错误 / by zero,暂停时间:2000
【2000】 ms 后第【2】次重试
2023-02-07 10:49:44 执行,结果:第3次业务正常执行...
Process finished with exit code 0
一直失败,直到超过重试次数抛异常退出
2023-02-07 10:46:33 执行,结果:系统错误 / by zero,暂停时间:1000
【1000】 ms 后第【1】次重试
2023-02-07 10:46:34 执行,结果:系统错误 / by zero,暂停时间:2000
【2000】 ms 后第【2】次重试
2023-02-07 10:46:36 执行,结果:系统错误 / by zero,暂停时间:4000
【4000】 ms 后第【3】次重试
2023-02-07 10:46:40 执行,结果:系统错误 / by zero,暂停时间:8000
【8000】 ms 后第【4】次重试
2023-02-07 10:46:48 执行,结果:系统错误 / by zero,暂停时间:16000
【16000】 ms 后第【5】次重试
2023-02-07 10:47:04 执行,结果:重试达到最大次数【5】
/ by zero
Exception in thread "main" java.lang.Exception: 请求退出,超出重试次数
at com.xcy.TryCatchReturnTry.main(TryCatchReturnTry.java:31)