package com.jingsong.test;
import cn.hutool.core.util.RandomUtil;
/**
* @author jingsong
* @date 2022/4/27 23:25
* @desc 进行某些非幂等性操作时(例如查询数据库),少数情况可能需要多次重试才能成功
*/
public class RetryTest {
public static void main(String[] args) {
String result = RetryUtil.retry(() -> {
// 模拟出来一个异常
if (RandomUtil.randomBoolean()) {
int i = 1 / 0;
}
return "方法执行成功啦~";
}, 3, 1000L);
System.out.println("result = " + result);
}
}
@SuppressWarnings("all")
class RetryUtil {
public static int DEFAULT_RETRY_TIMES = 3;
public static long DEFAULT_WAIT_TIME = 1000L;
public static <T> T retry(Function<T> func) {
return retry(func, DEFAULT_RETRY_TIMES, DEFAULT_WAIT_TIME);
}
public static <T> T retry(Function<T> func, int retryTimes, long waitTime) {
for (int i = 1; i <= retryTimes; i++) {
try {
return func.apply();
} catch (Exception e) {
// log function error
System.out.println("第" + i + "次出现异常啦~" + e);
// 不要多等一次
if (i == retryTimes) break;
try {
Thread.sleep(waitTime);
} catch (InterruptedException e1) {
// log sleep error
}
}
}
throw new RuntimeException("retry too many times:" + retryTimes);
}
}
interface Function<T> {
T apply();
}
utils009_非幂等性操作的重试机制
最新推荐文章于 2025-04-01 08:30:00 发布
本文探讨了在处理数据库查询等非幂等操作时,如何通过RetryUtil类实现3次重试机制,模拟异常并演示了如何在Java中使用Hutool库。着重展示了在遇到错误时如何优雅地处理和避免无限循环。
2659

被折叠的 条评论
为什么被折叠?



