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.
 
 

36 lines
1.3 KiB

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public class RetryUtils {
private static final long BASE_WAIT_MS = 500;
private static final int MAX_ATTEMPTS = 5;
public static <T> T executeWithRetry(Supplier<T> supplier) throws NetworkException {
int attempt = 0;
while (true) {
try {
return supplier.get();
} catch (Exception e) {
attempt++;
if (attempt >= MAX_ATTEMPTS) {
throw new NetworkException("重试失败,已达最大重试次数", e);
}
long waitTime = calculateWaitTime(attempt);
System.out.println("重试失败,等待 " + waitTime + "ms 后重试... (第 " + attempt + " 次尝试)");
try {
TimeUnit.MILLISECONDS.sleep(waitTime);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new NetworkException("重试被中断", ie);
}
}
}
}
private static long calculateWaitTime(int attempt) {
// 指数退避公式:wait = base * 2^attempt
return BASE_WAIT_MS * (long) Math.pow(2, attempt);
}
}