实现一个简单的RetryUtils

RetryUtils

public class RetryUtils {

    private static final int DEFAULT_RETRY = 3;

    private static final ExecuteFailedWarn DEFAULT_WARN_FUNCTION = System.out::println;

    private static final OutputFunction DEFAULT_OUTPUT = System.out::println;

    public static void call(int retryTimes, RunFunction runFunction, ExecuteFailedWarn failed, OutputFunction outputFunction) {
        int flag = 0;
        while (flag < retryTimes) {
           try {
               outputFunction.output(runFunction.execute());
               break;
           }catch (Exception e) {
               failed.failed("Retry for msg: " + e.getMessage());
               flag++;
           }
        }
    }

    public static void call(RunFunction runFunction, OutputFunction outputFunction) {
        RetryUtils.call(DEFAULT_RETRY, runFunction, DEFAULT_WARN_FUNCTION, outputFunction);
    }

    public static void call(RunFunction runFunction) {
        RetryUtils.call(DEFAULT_RETRY, runFunction,  DEFAULT_WARN_FUNCTION, DEFAULT_OUTPUT);
    }

    public static void call(int times, RunFunction runFunction) {
        RetryUtils.call(times, runFunction, DEFAULT_WARN_FUNCTION, DEFAULT_OUTPUT);
    }
}

OutputFunction

@FunctionalInterface
public interface OutputFunction {

    void output(Object res);
}

RunFunction

@FunctionalInterface
public interface RunFunction {

    Object execute() throws Exception;
}

ExecuteFailedWarn

@FunctionalInterface
public interface ExecuteFailedWarn {
    void failed(String msg);
}


test

public static void main(String[] args) {
      RetryUtils.call(3, () -> {
            if (System.currentTimeMillis()%19 != 0) {
                throw new Exception("adfasdfa");
            }
            return new Object();
        });
    }

你可能感兴趣的:(实现一个简单的RetryUtils)