使用easy-retry轻松进行任务重试

Easy-retry是一个Java任务重试框架。

项目主页:https://github.com/bournecui/easy-retry

主要特点

  • 灵活,可以设置不同的重试策略,比如
    • 发生异常时重试,你可以设置哪些异常被重试、哪些异常被忽略。
    • 返回值不符合预期时重置。

         也可以设置中断重试的策略,比如达到最大重试次数、达到最多等待时间等。

  • 易用
    • 短短几行代码就可以重试你的任务。
  • 轻量级
    • 除了slf4j、logback日志框架外,没有引入任何第三方Jar包。

如何使用

引入依赖

<dependency>
        <groupId>com.github.bournecui</groupId>
        <artifactId>easy-retry</artifactId>
        <version>0.0.1</version>
</dependency>

使用EasyRetryBuilder构建EasyRetry实例,它是线程安全的,所以在你的程序里构建一个就可以了。

EasyRetry easyRetry = EasyRetryBuilder.newBuilder()
                 .maxAttempts(10)
                 .includeExceptions(IllegalStateException.class)
                 .build();

使用EasyCallable(有返回值)或者EasyRunnable(没有返回值)封装你的任务并用easyRetry运行它。

Integer res1 = easyRetry.call(new EasyCallable<Integer>() {
            @Override
            public Integer call() {
                int aInt = (int) (Math.random() * 10);
                if (aInt % 3 != 0) {
                    throw new IllegalStateException(aInt + " is not expected!");
                }
                return aInt;
            }
        });

对于有返回值的任务,你可以使用ResultPredicate判断返回值是不是你想要的,如果不是你想要的,它会进行重试。

Integer res2 = easyRetry.call(new EasyCallable<Integer>() {
            @Override
            public Integer call() {
                return (int) (Math.random() * 10);
            }
        }, new ResultPredicate<Integer>() {
            @Override
            public boolean test(Integer result) {
                return result % 3 != 0;
            }
        });

如果你使用兰姆达表达式并static import来导入com.github.bournecui.easyretry.EasyRetryBuilder.newBuilder,你的代码看起来会更简洁。

newBuilder()
          .maxAttempts(10)
          .includeExceptions(IllegalStateException.class)
          .build()
          .call(() -> (int) (Math.random() * 10), result -> result % 3 != 0);

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值