package com.docus.server.archive.utils;

import com.docus.infrastructure.core.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * @author YongBin Wen
 * @date 2024/8/23 11:35
 */
public class MethodRetryUtil {
    private final static Logger logger = LoggerFactory.getLogger(MethodRetryUtil.class);

    public static <T> boolean retry(Consumer<T> consumer, T param, int retries, int timeoutMillis) {
        if (retries <= 0) {
            throw new BaseException("重试次数需要大于0");
        }
        for (int i = 1; i <= retries; i++) {
            try {
                consumer.accept(param);
                logger.info("重试操作成功，进行了 {} 次重试",i);
                return true;
            } catch (Exception rex) {
                logger.error("重试操作失败，尝试第" + (i + 1) + "次重试," + rex.getMessage(), rex);
                try {
                    TimeUnit.MILLISECONDS.sleep(timeoutMillis);
                } catch (InterruptedException exc) {
                    Thread.currentThread().interrupt();
                    return false;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        AtomicInteger i=new AtomicInteger(-1);
        System.out.println(retry(n -> {
            System.out.println(2 / n);
        }, 0, 10, 500));

    }
}
