首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >聊聊resilience4j的Retry

聊聊resilience4j的Retry

作者头像
code4it
发布于 2018-09-17 09:03:21
发布于 2018-09-17 09:03:21
1.2K00
代码可运行
举报
文章被收录于专栏:码匠的流水账码匠的流水账
运行总次数:0
代码可运行

本文主要研究一下resilience4j的Retry

Retry

resilience4j-retry-0.13.0-sources.jar!/io/github/resilience4j/retry/Retry.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * A Retry instance is thread-safe can be used to decorate multiple requests.
 * A Retry.
 */
public interface Retry {

    /**
     * Returns the ID of this Retry.
     *
     * @return the ID of this Retry
     */
    String getName();

    /**
     * Creates a retry Context.
     *
     * @return the retry Context
     */
    Retry.Context context();

    /**
     * Returns the RetryConfig of this Retry.
     *
     * @return the RetryConfig of this Retry
     */
    RetryConfig getRetryConfig();

    /**
     * Returns an EventPublisher can be used to register event consumers.
     *
     * @return an EventPublisher
     */
    EventPublisher getEventPublisher();

    /**
     * Creates a Retry with a custom Retry configuration.
     *
     * @param name the ID of the Retry
     * @param retryConfig a custom Retry configuration
     *
     * @return a Retry with a custom Retry configuration.
     */
    static Retry of(String name, RetryConfig retryConfig){
        return new RetryImpl(name, retryConfig);
    }

    /**
     * Creates a Retry with a custom Retry configuration.
     *
     * @param name the ID of the Retry
     * @param retryConfigSupplier a supplier of a custom Retry configuration
     *
     * @return a Retry with a custom Retry configuration.
     */
    static Retry of(String name, Supplier<RetryConfig> retryConfigSupplier){
        return new RetryImpl(name, retryConfigSupplier.get());
    }

    /**
     * Creates a retryable supplier.
     *
     * @param retry the retry context
     * @param supplier the original function
     * @param <T> the type of results supplied by this supplier
     *
     * @return a retryable function
     */
    static <T> Supplier<T> decorateSupplier(Retry retry, Supplier<T> supplier){
        return () -> {
            Retry.Context context = retry.context();
            do try {
                T result = supplier.get();
                context.onSuccess();
                return result;
            } catch (RuntimeException runtimeException) {
                context.onRuntimeError(runtimeException);
            } while (true);
        };
    }

    /**
     * Creates a retryable callable.
     *
     * @param retry the retry context
     * @param supplier the original function
     * @param <T> the type of results supplied by this supplier
     *
     * @return a retryable function
     */
    static <T> Callable<T> decorateCallable(Retry retry, Callable<T> supplier){
        return () -> {
            Retry.Context context = retry.context();
            do try {
                T result = supplier.call();
                context.onSuccess();
                return result;
            } catch (RuntimeException runtimeException) {
                context.onRuntimeError(runtimeException);
            } while (true);
        };
    }

    /**
     * Creates a retryable runnable.
     *
     * @param retry the retry context
     * @param runnable the original runnable
     *
     * @return a retryable runnable
     */
    static Runnable decorateRunnable(Retry retry, Runnable runnable){
        return () -> {
            Retry.Context context = retry.context();
            do try {
                runnable.run();
                context.onSuccess();
                break;
            } catch (RuntimeException runtimeException) {
                context.onRuntimeError(runtimeException);
            } while (true);
        };
    }
    //......
}
  • 这个类定义了一些工厂方法,最后new的是RetryImpl
  • 还定义了decorate开头的方法,包装retry的逻辑
  • retry逻辑是包装在一个循环里头,先执行业务代码,如果成功调用context.onSuccess(),跳出循环,如果失败捕获RuntimeException,然后调用context.onRuntimeError

RetryConfig

resilience4j-retry-0.13.0-sources.jar!/io/github/resilience4j/retry/RetryConfig.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class RetryConfig {

    public static final int DEFAULT_MAX_ATTEMPTS = 3;
    public static final long DEFAULT_WAIT_DURATION = 500;
    public static final IntervalFunction DEFAULT_INTERVAL_FUNCTION = (numOfAttempts) -> DEFAULT_WAIT_DURATION;
    public static final Predicate<Throwable> DEFAULT_RECORD_FAILURE_PREDICATE = (throwable) -> true;

    private int maxAttempts = DEFAULT_MAX_ATTEMPTS;

    private IntervalFunction intervalFunction = DEFAULT_INTERVAL_FUNCTION;
    // The default exception predicate retries all exceptions.
    private Predicate<Throwable> exceptionPredicate = DEFAULT_RECORD_FAILURE_PREDICATE;

    //......
}
  • 该配置主要有3个参数,一个是maxAttempts,一个是exceptionPredicate,一个是intervalFunction

Retry.Context

resilience4j-retry-0.13.0-sources.jar!/io/github/resilience4j/retry/Retry.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
   interface Context {

        /**
         *  Records a successful call.
         */
        void onSuccess();

        /**
         * Handles a checked exception
         *
         * @param exception the exception to handle
         * @throws Throwable the exception
         */
        void onError(Exception exception) throws Throwable;

        /**
         * Handles a runtime exception
         *
         * @param runtimeException the exception to handle
         */
        void onRuntimeError(RuntimeException runtimeException);
    }
  • 这个接口定义了onSuccess、onError、onRuntimeError

RetryImpl.ContextImpl

resilience4j-retry-0.13.0-sources.jar!/io/github/resilience4j/retry/internal/RetryImpl.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
   public final class ContextImpl implements Retry.Context {

        private final AtomicInteger numOfAttempts = new AtomicInteger(0);
        private final AtomicReference<Exception> lastException = new AtomicReference<>();
        private final AtomicReference<RuntimeException> lastRuntimeException = new AtomicReference<>();

        private ContextImpl() {
        }

        public void onSuccess() {
            int currentNumOfAttempts = numOfAttempts.get();
            if(currentNumOfAttempts > 0){
                succeededAfterRetryCounter.increment();
                Throwable throwable = Option.of(lastException.get()).getOrElse(lastRuntimeException.get());
                publishRetryEvent(() -> new RetryOnSuccessEvent(getName(), currentNumOfAttempts, throwable));
            }else{
                succeededWithoutRetryCounter.increment();
            }
        }

        public void onError(Exception exception) throws Throwable{
            if(exceptionPredicate.test(exception)){
                lastException.set(exception);
                throwOrSleepAfterException();
            }else{
                failedWithoutRetryCounter.increment();
                publishRetryEvent(() -> new RetryOnIgnoredErrorEvent(getName(), exception));
                throw exception;
            }
        }

        public void onRuntimeError(RuntimeException runtimeException){
            if(exceptionPredicate.test(runtimeException)){
                lastRuntimeException.set(runtimeException);
                throwOrSleepAfterRuntimeException();
            }else{
                failedWithoutRetryCounter.increment();
                publishRetryEvent(() -> new RetryOnIgnoredErrorEvent(getName(), runtimeException));
                throw runtimeException;
            }
        }

        private void throwOrSleepAfterException() throws Exception {
            int currentNumOfAttempts = numOfAttempts.incrementAndGet();
            Exception throwable = lastException.get();
            if(currentNumOfAttempts >= maxAttempts){
                failedAfterRetryCounter.increment();
                publishRetryEvent(() -> new RetryOnErrorEvent(getName(), currentNumOfAttempts, throwable));
                throw throwable;
            }else{
                waitIntervalAfterFailure(currentNumOfAttempts, throwable);
            }
        }

        private void throwOrSleepAfterRuntimeException(){
            int currentNumOfAttempts = numOfAttempts.incrementAndGet();
            RuntimeException throwable = lastRuntimeException.get();
            if(currentNumOfAttempts >= maxAttempts){
                failedAfterRetryCounter.increment();
                publishRetryEvent(() -> new RetryOnErrorEvent(getName(), currentNumOfAttempts, throwable));
                throw throwable;
            }else{
                waitIntervalAfterFailure(currentNumOfAttempts, throwable);
            }
        }

        private void waitIntervalAfterFailure(int currentNumOfAttempts, Throwable throwable) {
            // wait interval until the next attempt should start
            long interval = intervalFunction.apply(numOfAttempts.get());
            publishRetryEvent(()-> new RetryOnRetryEvent(getName(), currentNumOfAttempts, throwable, interval));
            Try.run(() -> sleepFunction.accept(interval))
                    .getOrElseThrow(ex -> lastRuntimeException.get());
        }

    }
  • throwOrSleepAfterRuntimeException方法会根据重试次数判断,如果超出则抛lastRuntimeException,如果不超出则调用waitIntervalAfterFailure
  • waitIntervalAfterFailure则通过sleepFunction来进行延时

小结

  • resilience4j的Retry沿用了该组件的一贯风格,通过decorate方法来织入重试的逻辑
  • 重试的逻辑就是一个while true循环,先执行业务方法,如果成功则调用Retry.Context的onSuccess方法,然后跳出循环,如果失败的话,只捕获RuntimeException,然后调用Retry.Context的onRuntimeError
  • onRuntimeError会先判断该异常是否需要重试,如果不需要则直接抛出原有异常,需要重试的话,则numOfAttempts.incrementAndGet(),如果超出限制则抛出异常,没有超出限制则根据配置的重试间隔进行sleep,然后onRuntimeError返回继续下一循环重试。

doc

  • Resilience4j is a fault tolerance library designed for Java8 and functional programming
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-07-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码匠的流水账 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
[python]numba安装后测试代码
​主要任务是有两组bboxs,进行匹配,计算iou阈值,如果直接用for循环,需要写两个for循环,时间复杂度还是很大的 因此尝试使用numba对循环进行加速,具体代码如下:
云未归来
2025/07/17
840
Python 提速大杀器之 numba 篇
你是不是曾经有这样的苦恼,python 真的太好用了,但是它真的好慢啊(哭死) ; C++ 很快,但是真的好难写啊,此生能不碰它就不碰它。老天啊,有没有什么两全其美的办法呢?俗话说的好:办法总是比困难多,大家都有这个问题,自然也就有大佬来试着解决这个问题,这就请出我们今天的主角: numba
OpenMMLab 官方账号
2022/01/18
3.2K0
Python加速运行技巧
Python 是一种脚本语言,相比 C/C++ 这样的编译语言,在效率和性能方面存在一些不足。但是,有很多时候,Python 的效率并没有想象中的那么夸张。本文对一些 Python 代码加速运行的技巧进行整理。
小萌哥
2020/07/24
1.3K0
利用numba給Python代码加速 [1]
Numba @jit 装饰器有两种编译模式, Nopython 模式和Object 模式。nopython编译模式的行为本质上是编译修饰后的函数,使其完全运行而不需要Python解释器的参与。这是使用Numba jit装饰器的推荐和最佳实践方法,因为它可以获得最佳性能。@jit(nopython=True) 等效于@njit()。
用户6021899
2022/01/10
1.8K0
利用numba給Python代码加速 [1]
让python快到飞起-numba加速
python是一门高效动态编程语言,由于其采用简洁明了的语法以及灵活性深受大家欢迎。但是,这既是它最大的优势,也是最大的劣势。它的灵活性和无类型的高级语法可能会导致数据和计算密集型程序的性能不佳,因为运行本地编译代码要比运行动态解释代码快很多倍。
自学气象人
2022/11/02
1.1K0
让python快到飞起-numba加速
Python NumPy缓存优化与性能提升
NumPy 是 Python 中进行科学计算和数据处理的核心库,其强大的多维数组操作功能让其在计算密集型任务中表现优异。然而,当处理大规模数据时,性能问题可能成为瓶颈。合理地利用 NumPy 的缓存机制和优化策略,可以显著提升计算效率。
sergiojune
2024/12/23
4260
Python NumPy缓存优化与性能提升
利用numba給Python代码加速 [2]
Numba 的 @vectorize 装饰器可以将以标量为输入的的python函数编译为类似Numpy的 ufuncs。创建一个传统的NumPy ufunc并不是最简单的过程,它可能需要编写一些C代码。Numba让这很容易。使用@vectorize装饰器 ,Numba可以将纯Python函数编译成ufunc,该ufunc在NumPy数组上运行的速度与用C编写的传统ufunc一样快。
用户6021899
2022/01/10
9980
利用numba給Python代码加速 [2]
Python Numpy性能提升的利器Numa优化技巧
在数据分析和科学计算中,Python和Numpy是非常流行的工具组合。然而,随着数据量的增加,Python解释器在处理大规模数组时的性能可能无法满足需求。为了提升Python代码的执行效率,Numba成为了一个强大的工具。Numba是一个基于LLVM的即时编译器,它可以将Python代码编译为高效的机器代码,从而极大地提升Numpy数组操作的性能。
sergiojune
2024/10/21
4790
Python Numpy性能提升的利器Numa优化技巧
numba,让你的Python飞起来!
python由于它动态解释性语言的特性,跑起代码来相比java、c++要慢很多,尤其在做科学计算的时候,十亿百亿级别的运算,让python的这种劣势更加凸显。
Python进阶者
2019/09/17
1.5K0
numba,让你的Python飞起来!
使用numba加速python科学计算
python作为一门编程语言,有非常大的生态优势,但是其执行效率一直被人诟病。纯粹的python代码跑起来速度会非常的缓慢,因此很多对性能要求比较高的python库,需要用C++或者Fortran来构造底层算法模块,再用python进行上层封装的方案。在前面写过的这篇博客中,介绍了使用f2py将fortran代码编译成动态链接库的方案,这可以认为是一种“事前编译”的手段。但是本文将要介绍一种即时编译(Just In Time,简称JIT)的手段,也就是在临近执行函数前,才对其进行编译。以下截图来自于参考链接4,讲述了关于常见的一些编译场景的区别:
DechinPhy
2021/05/21
2.1K0
优化Python代码性能的实用技巧
在编写Python代码时,性能优化是一个重要的考虑因素。今天我将介绍一些实用的技巧,帮助大家优化Python代码性能,并提供详细的代码示例。
华科云商小彭
2023/09/05
4570
优化Python代码性能的实用技巧
numba,让你的Python飞起来!
python由于它动态解释性语言的特性,跑起代码来相比java、c++要慢很多,尤其在做科学计算的时候,十亿百亿级别的运算,让python的这种劣势更加凸显。
派大星的数据屋
2022/04/02
1.3K0
numba,让你的Python飞起来!
用 Numba 加速 Python 代码,变得像 C++ 一样快
注意: 这篇文章的 Jupyter Notebook 代码在我的 Github 上:SpeedUpYourAlgorithms-Numba
昱良
2019/07/04
3K0
用 Numba 加速 Python 代码,变得像 C++ 一样快
NumPy 高级教程——并行计算
并行计算是在多个处理单元上同时执行计算任务的方法,以提高程序的性能。在 NumPy 中,可以使用一些工具和技术来进行并行计算,充分利用多核处理器的优势。在本篇博客中,我们将深入介绍 NumPy 中的并行计算,并通过实例演示如何应用这些技术。
Echo_Wish
2024/01/08
1.7K0
强化学习技巧五:numba提速python程序
numba是一款可以将python函数编译为机器代码的JIT编译器,经过numba编译的python代码(仅限数组运算),其运行速度可以接近C或FORTRAN语言。
汀丶人工智能
2022/12/21
1.1K0
强化学习技巧五:numba提速python程序
OpenCV算法库
numba是一个用于编译Python数组和数值计算函数的编译器,这个编译器能够大幅提高直接使用Python编写的函数的运算速度。
@小森
2024/03/15
2140
用Numba加速Python代码
说这句话的人也没有错。与许多其他编程语言相比,Python很慢。Benchmark game有一些比较不同编程语言在不同任务上的速度的可靠的基准。
AiTechYun
2019/07/04
2.4K0
【图像配准】图像融合再探索/图像像素点遍历加速
在我先前的博文【图像配准】多图配准/不同特征提取算法/匹配器比较测试中,提到了图像融合的一种方式,相关代码如下:
zstar
2023/02/16
8660
python中for循环语句例子_python怎么循环1到8不要4
这篇文章主要介绍了python中关于for循环使用过程中的碎碎念,需要的朋友可以参考下
全栈程序员站长
2022/09/22
1.3K0
[Python技巧]如何加快循环操作和Numpy数组运算速度
在 24式加速你的Python中介绍对循环的加速方法中,一个办法就是采用 Numba 加速,刚好最近看到一篇文章介绍了利用 Numba 加速 Python ,文章主要介绍了两个例子,也是 Numba 的两大作用,分别是加速循环,以及对 Numpy 的计算加速。
kbsc13
2019/08/16
10.3K0
相关推荐
[python]numba安装后测试代码
更多 >
交个朋友
加入架构与运维学习入门群
系统架构设计入门 运维体系构建指南
加入架构与运维工作实战群
高并发系统设计 运维自动化实践
加入前端学习入门群
前端基础系统教学 经验分享避坑指南
换一批
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档