Datax之自定义重试工具类RetryUtil

本文详细分析了阿里的datax库中的RetryUtil工具类,介绍了其提供的同步和异步重试方法,以及Retry和AsyncRetry类的实现原理,帮助开发者理解在处理业务逻辑失败时的重试逻辑选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:

在日常的开发中,针对某个业务逻辑,我们经常会有执行失败后再重试一次的需求。重试根据异常的不同则会有不同的方案。当然重试也不是失败后立即重试,有可能是等待固定时间后重试,也有可能是指数级等待时间重试,重试N次后则最终判定失败,不再重试。 

基于这种需求,阿里开源的datax工具中,也有相应的工具类,就是RetryUtil,笔者就来简单分析下这个util类。

1.datax之RetryUtil

public final class RetryUtil {

    private static final Logger LOG = LoggerFactory.getLogger(RetryUtil.class);

    private static final long MAX_SLEEP_MILLISECOND = 256 * 1000;
    /**
     * 重试次数工具方法.
     *
     * @param callable               实际逻辑
     * @param retryTimes             最大重试次数(>1)
     * @param sleepTimeInMilliSecond 运行失败后休眠对应时间再重试
     * @param exponential            休眠时间是否指数递增
     * @param <T>                    返回值类型
     * @return 经过重试的callable的执行结果
     */
    public static <T> T executeWithRetry(Callable<T> callable,
                                         int retryTimes,
                                         long sleepTimeInMilliSecond,
                                         boolean exponential) throws Exception {
        Retry retry = new Retry();
        return retry.doRetry(callable, retryTimes, sleepTimeInMilliSecond, exponential, null);
    }
    
    /**
     * 重试次数工具方法.
     *
     * @param callable               实际逻辑
     * @param retryTimes             最大重试次数(>1)
     * @param sleepTimeInMilliSecond 运行失败后休眠对应时间再重试
     * @param exponential            休眠时间是否指数递增
     * @param <T>                    返回值类型
     * @param retryExceptionClasss   出现指定的异常类型时才进行重试
     * @return 经过重试的callable的执行结果
     */
    public static <T> T executeWithRetry(Callable<T> callable,
                                         int retryTimes,
                                         long sleepTimeInMilliSecond,
                                         boolean exponential,
                                         List<Class<?>> retryExceptionClasss) throws Exception {
        Retry retry = new Retry();
        return retry.doRetry(callable, retryTimes, sleepTimeInMilliSecond, exponential, retryExceptionClasss);
    }

    /**
     * 在外部线程执行并且重试。每次执行需要在timeoutMs内执行完,不然视为失败。
     * 执行异步操作的线程池从外部传入,线程池的共享粒度由外部控制。比如,HttpClientUtil共享一个线程池。
     * <p/>
     * 限制条件:仅仅能够在阻塞的时候interrupt线程
     *
     * @param callable               实际逻辑
     * @param retryTimes             最大重试次数(>1)
     * @param sleepTimeInMilliSecond 运行失败后休眠对应时间再重试
     * @param exponential            休眠时间是否指数递增
     * @param timeoutMs              callable执行超时时间,毫秒
     * @param executor               执行异步操作的线程池
     * @param <T>                    返回值类型
     * @return 经过重试的callable的执行结果
     */
    public static <T> T asyncExecuteWithRetry(Callable<T> callable,
                                              int retryTimes,
                                              long sleepTimeInMilliSecond,
                                              boolean exponential,
                                              long timeoutMs,
                                              ThreadPoolExecutor executor) throws Exception {
        Retry retry = new AsyncRetry(timeoutMs, executor);
        return retry.doRetry(callable, retryTimes, sleepTimeInMilliSecond, exponential, null);
    }
}

RetryUtil共提供了三个方法,前两个都是同步调用(在调用者线程中执行重试),最后一个是异步调用(在给定的线程池中执行重试)。

前两个方法的唯一区别就是是否指定retryExceptionClasss类。我们一起来看下Retry类的具体操作

2.Retry类

private static class Retry {

    public <T> T doRetry(Callable<T> callable, int retryTimes, long sleepTimeInMilliSecond, boolean exponential, List<Class<?>> retryExceptionClasss)
        throws Exception {

        // 参数校验
        if (null == callable) {
            throw new IllegalArgumentException("系统编程错误, 入参callable不能为空 ! ");
        }

        if (retryTimes < 1) {
            throw new IllegalArgumentException(String.format(
                "系统编程错误, 入参retrytime[%d]不能小于1 !", retryTimes));
        }

        Exception saveException = null;
        for (int i = 0; i < retryTimes; i++) {
            try {
                // 执行方法调用
                return call(callable);
            } catch (Exception e) {
                saveException = e;
                if (i == 0) {
                    LOG.error(String.format("Exception when calling callable, 异常Msg:%s", saveException.getMessage()), saveException);
                }

                // 如果指定了对应的异常类,则判断当前e是否就是对应的异常类,是的话则执行重试,否则直接抛出异常
                if (null != retryExceptionClasss && !retryExceptionClasss.isEmpty()) {
                    boolean needRetry = false;
                    for (Class<?> eachExceptionClass : retryExceptionClasss) {
                        if (eachExceptionClass == e.getClass()) {
                            needRetry = true;
                            break;
                        }
                    }
                    if (!needRetry) {
                        throw saveException;
                    }
                }

                // 不超过最大重试次数则执行后续重试逻辑
                if (i + 1 < retryTimes && sleepTimeInMilliSecond > 0) {
                    long startTime = System.currentTimeMillis();

                    // 根据入参决定休息多久之后执行重试逻辑,最大不超过MAX_SLEEP_MILLISECOND
                    long timeToSleep;
                    if (exponential) {
                        timeToSleep = sleepTimeInMilliSecond * (long) Math.pow(2, i);
                        if(timeToSleep >= MAX_SLEEP_MILLISECOND) {
                            timeToSleep = MAX_SLEEP_MILLISECOND;
                        }
                    } else {
                        timeToSleep = sleepTimeInMilliSecond;
                        if(timeToSleep >= MAX_SLEEP_MILLISECOND) {
                            timeToSleep = MAX_SLEEP_MILLISECOND;
                        }
                    }

                    try {
                        // 当前执行线程沉睡
                        Thread.sleep(timeToSleep);
                    } catch (InterruptedException ignored) {
                    }

                    long realTimeSleep = System.currentTimeMillis()-startTime;

                    LOG.error(String.format("Exception when calling callable, 即将尝试执行第%s次重试.本次重试计划等待[%s]ms,实际等待[%s]ms, 异常Msg:[%s]",
                                            i+1, timeToSleep,realTimeSleep, e.getMessage()));

                }
            }
        }
        throw saveException;
    }

    protected <T> T call(Callable<T> callable) throws Exception {
        return callable.call();
    }
}

Retry重试逻辑还是比较简单的,根据不同的入参,控制重试的休眠事件以及是否重试的相关逻辑。

需要注意的是,重试中的休眠逻辑会直接在当前执行线程中执行,如果使用者不想休眠当前线程,可以考虑使用RetryUtil的第三个方法,也就是下面的AsyncRetry的逻辑。

3.AsyncRetry异步执行重试逻辑

// 直接继承了Retry类
private static class AsyncRetry extends Retry {

    private long timeoutMs;
    private ThreadPoolExecutor executor;

    public AsyncRetry(long timeoutMs, ThreadPoolExecutor executor) {
        this.timeoutMs = timeoutMs;
        this.executor = executor;
    }

    /**
         * 使用传入的线程池异步执行任务,并且等待。
         * <p/>
         * future.get()方法,等待指定的毫秒数。如果任务在超时时间内结束,则正常返回。
         * 如果抛异常(可能是执行超时、执行异常、被其他线程cancel或interrupt),都记录日志并且网上抛异常。
         * 正常和非正常的情况都会判断任务是否结束,如果没有结束,则cancel任务。cancel参数为true,表示即使
         * 任务正在执行,也会interrupt线程。
         *
         * @param callable
         * @param <T>
         * @return
         * @throws Exception
         */
    @Override
    protected <T> T call(Callable<T> callable) throws Exception {
        // 重写后的call()方法,在执行重试时,直接交由Executor执行,避免了当前线程被阻塞
        Future<T> future = executor.submit(callable);
        try {
            // 在规定时间内获取执行结果
            return future.get(timeoutMs, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            // 规定时间内没有获取到结果则直接抛出异常
            LOG.warn("Try once failed", e);
            throw e;
        } finally {
            if (!future.isDone()) {
                future.cancel(true);
                LOG.warn("Try once task not done, cancel it, active count: " + executor.getActiveCount());
            }
        }
    }
}

总结:

读者可以好好比较下Retry和AsyncRetry两者之间的区别。在适当的场景选择适当的重试对象。

使用自定义插件的datax的方法如下所示: 1. 首先,结合Airflow,您可以自己实现datax插件。可以通过读取connections获取数据源链接配置,然后生成datax的配置文件json,最后调用datax执行。 2. 您还可以按照datax的文档配置读取数据源和目标数据源,并执行调用命令来使用dataxdatax可以作为一个命令行工具使用,非常简单。 3. 对于那些喜欢集成化的数据转换工具的人来说,datax是一个很好的选择。datax是阿里巴巴开源的一款异构数据源同步工具。虽然看起来不怎么更新了,但在简单使用方面还是非常可靠的。您可以在https://github.com/alibaba/DataX 找到datax的相关信息。 总结来说,使用自定义插件的datax的方法是结合Airflow自己实现插件,或者按照datax的文档配置数据源并执行调用命令,或者直接使用datax作为集成化的数据转换工具。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Airflow自定义插件, 使用datax抽数](https://blog.csdn.net/seanxwq/article/details/109745723)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恐龙弟旺仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值