package com.jy.framework.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

/**
 * 重试工具类
 */
@Slf4j
public class RetryUtil {

    public static void execute(Runnable runnable) {
        execute(3, runnable);
    }

    public static <T> T execute(Supplier<T> supplier) {
        return execute(3, supplier);
    }

    public static void execute(int num, Runnable runnable) {
        for (int i = 0; i < num; i++) {
            try {
                runnable.run();
                return;
            } catch (Exception e) {
                log.info("第{}次重试失败", i, e);
                if (i == num - 1) {
                    throw e;
                }
            }
        }
    }

    public static <T> T execute(int num, Supplier<T> supplier) {
        for (int i = 0; i < num; i++) {
            try {
                return supplier.get();
            } catch (Exception e) {
                log.info("第{}次重试失败", i, e);
                if (i == num - 1) {
                    throw e;
                }
            }
        }
        return supplier.get();
    }

}
