Java 8 实现一个简单的错误重试工具类

Java 8 实现一个简单的错误重试工具类

首先实现这个工具类需要熟悉一下Java 8的函数式编程或者对匿名内部类的实现方式

知识储备:

最好熟悉一下 Java 8 函数式编程一些常见的函数式接口,比如:Consumer/Supplier ...

因为使用 Lambda 实现相对实现内部类的方式更加简洁和直观

代码实现:

这个工具类的实现非常的简单,现在直接上代码:

import java.util.List;
import java.util.function.Consumer;

/**
 * 错误重试工具类
 *
 * @author hdfg159
 * @date 2020/8/4 23:27
 */
public abstract class RetryUtils {
    /**
     * 重试调度方法
     *
     * @param dataSupplier
     *      返回数据方法执行体
     * @param exceptionCaught
     *      出错异常处理(包括第一次执行和重试错误)
     * @param retryCount
     *      重试次数
     * @param sleepTime
     *      重试间隔睡眠时间(注意:阻塞当前线程)
     * @param expectExceptions
     *      期待异常(抛出符合相应异常时候重试),空或者空容器默认进行重试
     * @param <R>
     *      数据类型
     *
     * @return R
     */
    public static <R> R invoke(Supplier<R> dataSupplier, Consumer<Throwable> exceptionCaught, int retryCount, long sleepTime, List<Class<? extends Throwable>> expectExceptions) {
        Throwable ex;
        try {
            // 产生数据
            return dataSupplier == null ? null : dataSupplier.get();
        } catch (Throwable throwable) {
            // 捕获异常
            catchException(exceptionCaught, throwable);
            ex = throwable;
        }

        if (expectExceptions != null && !expectExceptions.isEmpty()) {
            // 校验异常是否匹配期待异常
            Class<? extends Throwable> exClass = ex.getClass();
            boolean match = expectExceptions.stream().anyMatch(clazz -> clazz == exClass);
            if (!match) {
                return null;
            }
        }

        // 匹配期待异常或者允许任何异常重试
        for (int i = 0; i < retryCount; i++) {
            try {
                if (sleepTime > 0) {
                    Thread.sleep(sleepTime);
                }
                return dataSupplier.get();
            } catch (InterruptedException e) {
                System.err.println("thread interrupted !! break retry,cause:" + e.getMessage());
                // 恢复中断信号
                Thread.currentThread().interrupt();
                // 线程中断直接退出重试
                break;
            } catch (Throwable throwable) {
                catchException(exceptionCaught, throwable);
            }
        }

        return null;
    }

    private static void catchException(Consumer<Throwable> exceptionCaught, Throwable throwable) {
        try {
            if (exceptionCaught != null) {
                exceptionCaught.accept(throwable);
            }
        } catch (Throwable e) {
            log.error("retry exception caught throw error:{}", e.getMessage());
        }
    }

    /**
     * 函数式接口可以抛出异常
     *
     * @param <T>
     */
    @FunctionalInterface
    public interface Supplier<T> {
        
        /**
         * Gets a result.
         *
         * @return a result
         *
         * @throws Exception 错误时候抛出异常
         */
        T get() throws Exception;
    }
}

附上一个简单的测试用例和用法:

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        String error = RetryUtils.invoke(() -> {
            // 返回数据的代码编写
            // return "test";
            throw new RuntimeException("error");
        }, throwable -> System.out.println("error"), 3, 5_000, new ArrayList<>());
        // 输出返回数据
        System.out.println(error);
    }
}

温馨提示

RxJava 的同学可以使用 Retry 操作符实现同样的功能哦,RxJava 是非常强大操作符工具

工具类优化

以前的工具类难以满足需求,而且有缺陷,现在更新一下

主要优化点

  • 对异常重试的判断,不在固定异常列表重试

  • 对重试异常处理的优化,重试只针对异常重试的判断,不是无脑重试

  • 不支持非运行时异常

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

@Slf4j
public abstract class RetryUtils {

    public static <R> R invoke(Function<RetryContext, R> dataMapping,
                               int retryCount,
                               long sleepTime) {
        return invoke(dataMapping, retryCount, sleepTime, null, null);
    }

    public static <R> R invoke(Function<RetryContext, R> dataMapping,
                               int retryCount,
                               long sleepTime,
                               Predicate<RetryContext> exceptionFilter,
                               Consumer<RetryContext> exceptionCaught) {
        var context = RetryContext.init(sleepTime, retryCount, exceptionFilter, exceptionCaught);

        Exception finalException = null;

        while (context.getAlreadyRetryCount() < context.getRetryCount() + 1) {
            try {
                return (dataMapping == null) ? null : dataMapping.apply(context);
            } catch (Exception e) {
                finalException = e;

                if (context.getAlreadyRetryCount() >= context.getRetryCount()) {
                    break;
                }

                context.incrementAlreadyRetryCount();
                context.setException(e);
                if (!context.getExceptionFilter().test(context)) {
                    throw e;
                }

                try {
                    context.getExceptionCaught().accept(context);
                } catch (Exception caughtEx) {
                    log.error("Retry exception caught throw:{}", caughtEx.getMessage());
                }
            }

            var sleepMillis = context.getSleepMillis();
            if (sleepMillis > 0) {
                try {
                    Thread.sleep(sleepMillis);
                } catch (InterruptedException e) {
                    log.error("Thread interrupted,retry(sum):{}", context.getAlreadyRetryCount());

                    Thread.currentThread().interrupt();
                    throw new RetryFailException(finalException, context.getAlreadyRetryCount());
                }
            }
        }

        throw new RetryFailException(finalException, context.getRetryCount());
    }

    @Getter
    public static class RetryFailException extends RuntimeException {
        private final int retryCount;

        public RetryFailException(Throwable cause, int retryCount) {
            super(cause);
            this.retryCount = retryCount;
        }
    }

    @Getter
    public static class RetryContext {
        private int retryCount;
        private int alreadyRetryCount;

        private long sleepMillis;
        private final Map<String, Object> data = new HashMap<>();

        private Throwable exception;
        private Predicate<RetryContext> exceptionFilter = context -> true;
        /**
         * 符合 exceptionFilter 的异常捕获处理
         */
        private Consumer<RetryContext> exceptionCaught = context -> {};

        private RetryContext() {
        }

        public static RetryContext init(
            long sleepMillis,
            int retryCount,
            Predicate<RetryContext> exceptionFilter,
            Consumer<RetryContext> exceptionCaught) {
            if (retryCount <= 0) {
                throw new IllegalArgumentException("retryCount must be greater than 0");
            }

            var context = new RetryContext();
            context.retryCount = retryCount;
            context.sleepMillis = sleepMillis;

            if (exceptionFilter != null) {
                context.exceptionFilter = exceptionFilter;
            }

            if (exceptionCaught != null) {
                context.exceptionCaught = exceptionCaught;
            }
            return context;
        }

        public RetryContext setSleepMillis(long sleepMillis) {
            this.sleepMillis = sleepMillis;
            return this;
        }

        public RetryContext incrementRetryCount(int count) {
            this.retryCount += count;
            return this;
        }

        public RetryContext incrementAlreadyRetryCount() {
            this.alreadyRetryCount++;
            return this;
        }

        public RetryContext incrementAlreadyRetryCount(int count) {
            this.alreadyRetryCount += count;
            return this;
        }

        public RetryContext setException(Throwable exception) {
            this.exception = exception;
            return this;
        }
    }
}

后续优化反向

工具类还是不够好用,大家可以尝试往下面几方面优化:

  1. 支持重试上下文,每次重试传递数据
  2. 重试时间间隔优化,可以根据不同数据或者不同次数产生不同重试间隔时间
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。