1、代码
package com.wangzhan.controller;
public class RetryExecutorUtil {
private int maxRetries;
private long delay;
private int backoff;
public RetryExecutorUtil() {
}
public RetryExecutorUtil(int maxRetries, long delay, int backoff) {
this.maxRetries = maxRetries;
this.delay = delay;
this.backoff = backoff;
}
public Object execute(RetryCallback retryCallback) throws InterruptedException {
Exception lastException = null;
for (int i = 0; i < maxRetries; ++i) {
try {
return retryCallback.doInRetry();
} catch (Exception e) {
lastException = e;
Thread.sleep(delay * ((long)Math.pow(backoff, i)));
}
}
throw new RuntimeException("重试 " + maxRetries + " 次之后失败", lastException);
}
interface RetryCallback {
Object doInRetry();
}
public static void main(String[] args) throws InterruptedException {
RetryExecutorUtil retryExecutorUtil = new RetryExecutorUtil(3, 1000L, 2);
Object data = null;
try {
data = retryExecutorUtil.execute(() -> {
if (Math.random() > 0.99) {
System.out.println("数据获取成功!!!");
return "data";
} else {
System.out.println("获取数据失败, 重试中...");
throw new RuntimeException("获取数据失败");
}
});
} catch (RuntimeException e) {
System.out.println("捕获异常的数据。。。。。。。。");
e.printStackTrace();
return;
}
}
}
2、执行结果
