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. 重试时间间隔优化,可以根据不同数据或者不同次数产生不同重试间隔时间
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,183评论 6 516
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,850评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,766评论 0 361
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,854评论 1 299
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,871评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,457评论 1 311
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,999评论 3 422
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,914评论 0 277
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,465评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,543评论 3 342
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,675评论 1 353
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,354评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,029评论 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,514评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,616评论 1 274
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,091评论 3 378
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,685评论 2 360