美文网首页
实现一个简单的RetryUtils

实现一个简单的RetryUtils

作者: 五洋捉鳖zz | 来源:发表于2020-10-28 09:38 被阅读0次

    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

          本文链接:https://www.haomeiwen.com/subject/xfdxvktx.html