retry快速重试

1.引用guava中的重试类

            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>30.1.1-jre</version>
            </dependency>

2.定义Boolean类型的retry,通过返回结构true还是false来判断是否需要重试

Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
                .retryIfResult(Predicates.isNull())
                .retryIfResult(Predicates.equalTo(false))
                .retryIfExceptionOfType(IOException.class)
                .retryIfExceptionOfType(SocketTimeoutException.class)
                .retryIfExceptionOfType(ConnectException.class)
                .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
                .retryIfRuntimeException().withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();

说明
retryIfResult: 基于结果的判断是否retry,Predicates.isNull代表结果是null,Predicates.equalTo(false)代表结果是false
retryIfExceptionOfType: 基于执行过程中抛出的异常来判断是否进行重试,IOException,SocketTimeoutException,ConnectException三种异常类型会进行自动重试
retryIfRuntimeException: 如果运行时异常也进行重试
withWaitStrategy: 代表重试策略的间隔,WaitStrategies.fixedWait(3, TimeUnit.SECONDS)代表每隔3秒重试一次
withStopStrategy: 代表最多重试几次后停止

3.使用重试策略进行业务流程的调用

            Boolean isSuccess = retryer.call(() -> {
                MessagePushResult sendResult = sender.send(
                        context.alarmNotification.getReceivers().stream().map(ContactDto::getEnName).collect(Collectors.toSet()),
                        context.alarmNotification.getNotifyTitle(),
                        context.alarmNotification.getNotifyMsg(),
                        null);
                log.info("@@ Call Api ,response : {}", JsonUtils.toJSONString(sendResult));
                return sendResult.getCode() == TimlineContext.TIMLINE_SEND_SUCCESS;
            });

如果业务调用过程中sender.send方法抛了RuntimeException,IOException,SocketTimeoutException,ConnectException4种异常时,或者最后的return 结果是false,按照3秒间隔重试3次,直到最后返回结果是true

posted @   SpecialSpeculator  阅读(180)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2016-12-08 Python多进程----从入门到放弃
点击右上角即可分享
微信分享提示