package com.jingsong.test;
import cn.hutool.core.util.RandomUtil;
public class RetryTest {
    public static void main(String[] args) {
        String result = RetryUtil.retry(() -> {
            
            if (RandomUtil.randomBoolean()) {
                int i = 1 / 0;
            }
            return "方法执行成功啦~";
        }, 3, 1000L);
        System.out.println("result = " + result);
    }
}
@SuppressWarnings("all")
class RetryUtil {
    public static int DEFAULT_RETRY_TIMES = 3;
    public static long DEFAULT_WAIT_TIME = 1000L;
    public static <T> T retry(Function<T> func) {
        return retry(func, DEFAULT_RETRY_TIMES, DEFAULT_WAIT_TIME);
    }
    public static <T> T retry(Function<T> func, int retryTimes, long waitTime) {
        for (int i = 1; i <= retryTimes; i++) {
            try {
                return func.apply();
            } catch (Exception e) {
                
                System.out.println("第" + i + "次出现异常啦~" + e);
                
                if (i == retryTimes) break;
                try {
                    Thread.sleep(waitTime);
                } catch (InterruptedException e1) {
                    
                }
            }
        }
        throw new RuntimeException("retry too many times:" + retryTimes);
    }
}
interface Function<T> {
    T apply();
}