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
标签:retryIfExceptionOfType,false,重试,retry,Predicates,guava,快速 From: https://www.cnblogs.com/PythonOrg/p/16965475.html