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.
40 lines
1.1 KiB
40 lines
1.1 KiB
package com.example.datacollect.utils;
|
|
|
|
/**
|
|
* 指数退避重试工具类
|
|
* wait = 500 * 2^attempt
|
|
*/
|
|
public class RetryUtils {
|
|
|
|
// 基础延迟 500ms
|
|
private static final long BASE_DELAY_MS = 500;
|
|
|
|
@FunctionalInterface
|
|
public interface RetryTask<T> {
|
|
T run() throws Exception;
|
|
}
|
|
|
|
/**
|
|
* 执行带指数退避的重试
|
|
* @param maxRetries 最大重试次数(不含第一次)
|
|
* @param task 要执行的任务
|
|
* @return 执行结果
|
|
* @throws Exception 最后一次失败抛出
|
|
*/
|
|
public static <T> T retry(int maxRetries, RetryTask<T> task) throws Exception {
|
|
int attempt = 0;
|
|
while (true) {
|
|
try {
|
|
return task.run();
|
|
} catch (Exception e) {
|
|
if (attempt >= maxRetries) {
|
|
throw e; // 重试次数用完,抛出
|
|
}
|
|
// 指数退避:500 * 2^attempt
|
|
long delay = BASE_DELAY_MS * (1L << attempt);
|
|
Thread.sleep(delay);
|
|
attempt++;
|
|
}
|
|
}
|
|
}
|
|
}
|