You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

41 lines
1.4 KiB

public class RetryUtils {
private static final long BASE_WAIT_MS = 500;
private static final int MAX_RETRY = 5;
@FunctionalInterface
public interface RetryTask<T> {
T execute() throws Exception;
}
public static <T> T retry(RetryTask<T> task) throws Exception {
int attempt = 0;
while (attempt < MAX_RETRY) {
try {
return task.execute();
} catch (Exception e) {
attempt++;
if (attempt >= MAX_RETRY) {
System.out.println("最终失败: " + e.getMessage());
throw e;
}
long waitTime = BASE_WAIT_MS * (1L << attempt);
System.out.println("尝试执行 #" + attempt + "... 失败");
System.out.println("等待: " + waitTime + "ms");
try {
Thread.sleep(waitTime);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
}
}
}
throw new IllegalStateException("重试逻辑异常");
}
public static void main(String[] args) throws Exception {
RetryUtils.retry(() -> {
System.out.println("尝试执行");
throw new RuntimeException("模拟失败");
});
}
}