简单的java重试 小工具

160 阅读1分钟

不想引用太多的框架,不想写太复杂的逻辑,只想有一个通用的异常重试工具。

@Slf4j
public class RetryUtil {
    private static final int MAX_RETRIES = 3; // 最大重试次数
    private static final int DELAY_MILLIS = 1000*60; // 每次重试之间的等待时间(毫秒)

    public static <T> T executeWithRetry(Callable<T> task) throws Exception {
        for (int attempt = 0; attempt < MAX_RETRIES; attempt++) {
            try {
                return task.call(); // 执行任务
            } catch (Exception e) {
                if (attempt < MAX_RETRIES - 1) {
                    // 如果不是最后一次重试,则等待一段时间后再重试
                    Thread.sleep(DELAY_MILLIS);
                    log.info("重试中 ...");
                } else {
                    // 如果是最后一次重试且仍然失败,则抛出异常
                    throw e;
                }
            }
        }
        // 如果代码执行到这里,说明循环被意外中断(理论上不应该发生)
        throw new IllegalStateException("Retry loop failed unexpectedly");
    }


    public static void main(String[] args) {
        try {
            String result = executeWithRetry(() -> {
                double random = Math.random();
                System.out.println(random);
                // 这里模拟一个可能会失败的任务
                if (random <0.5) {
                    throw new RuntimeException("Task failed");
                }
                return "Task succeeded";
            });
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}