重试机制Guava Retryer的使用,及其注册自定义监听器Listener
2020-06-16 15:22
260 查看
重试机制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() + "次重试---------"); } }
相关文章推荐
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- 在spring中使用自定义注解注册监听器的方法
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- 在spring中使用自定义注解注册监听器
- guava-retrying重试工具库: Retryer.call()使用注意事项
- 【LISTENER】使用Oracle隐含参数禁止“_XPT”服务注册到监听器
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- guava的重试机制guava-retrying使用
- 使用Guava retryer优雅的实现接口重调机制
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- 如何在Listener(监听器)中使用spring容器管理的bean(自定义监听使用spring管理的bean)
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- Spring自定义Listener(监听器)的使用(在listener中调用sprng的bean需要特别注意)...
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean - fjdingsd
- 【Java.Web】监听器 —— Listener(*** 使用自定义Listener进行初始化工作 ***)
- 使用反射机制深入理解AOP机制并自定义AOP管理模块
- 在MIDP2.0中使用Push注册机制,允许应用被自动启动的方法
- Android 自定义View及其在布局文件中的使用示例