重试机制Guava Retryer的使用,及其注册自定义监听器Listener
在项目中我们一般需要远程调用其他服务,但是由于网络异常或者其他原因可能导致调用失败,此时我们就需要考虑使用重试机制,重复调用远程服务,避免由于一次调用失败导致任务执行失败的情况。
重试机制有很多的实现方式,现在介绍比较’‘优雅’'的一种重试机制:Guava Retryer
直接上代码吧:
public class RetryerDemo {
public static void main(String[] args) throws Exception{
// 定义重试类Retryer
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
// 定义重试条件
.retryIfException() // 异常
.retryIfRuntimeException() // 运行时异常
.retryIfExceptionOfType(Exception.class)
.retryIfException(Predicates.<Throwable>equalTo(new Exception()))
.retryIfResult(Predicates.equalTo(false))
// 定义等待策略,即每次的间隔时间
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
// 定义停止策略,即重试多少次
.withStopStrategy(StopStrategies.stopAfterAttempt(6))
// 定义时间限制,即每次请求不超过多少时间
.withAttemptTimeLimiter(AttemptTimeLimiters.<Boolean>fixedTimeLimit(2, TimeUnit.SECONDS))
// 注册监听器,每次调用重试方法都会触发监听器
.withRetryListener(new RetryerListener())
.build();
// 定义请求任务
Callable<Boolean> callable = new Callable<Boolean>() {
// 该方法为需要执行的任务,也就是需要远程调用服务的地方
public Boolean call() throws Exception {
return false;
}
};
// 使用重试类调用任务
retryer.call(callable);
}
}
/*
* 监听类,每次重试都会自动触发监听器
* 可在监听类中处理调用失败逻辑代码:如多次调用失败可发送邮件提醒等
**/
public class RetryerListener implements RetryListener {
public <V> void onRetry(Attempt<V> attempt) {
System.out.println("监听器被触发");
System.out.println("--------第" + attempt.getAttemptNumber() + "次重试---------");
}
}