定义需要重试的方法函数
public interface Function<T> {
T func();
}
定义重试的基本逻辑
public interface Retry<T> {
Logger log = LoggerFactory.getLogger(Retry.class);
/**
* 默认重试方法
*
* @param retry
* @return
*/
default T retry(Function<T> retry) {
int seconds = 30;
int retryTimes = 3; // 重试次数
for (int i = 1; i <= retryTimes; i++) {
try {
return retry.func();
} catch (Exception e) {
int sleepSeconds = seconds * i;
log.error("异常[次数:" + i + "/" + retryTimes + "],休眠" + sleepSeconds + "秒:", e);
CommonUtils.sleep(sleepSeconds);
if (i == retryTimes) {
throw new RuntimeException("已重试" + i + "次,仍异常,抛出异常", e);
}
}
}
throw new RuntimeException("Retry未知异常");
}
}
使用示例
public class Demo implements Retry<DemoResp> {
public void demo() {
// 这里会重试,成功后返回对应泛型的类变量
DemoResp resp = retry(() -> 您要重试的方法());
}
}