一、Fast-Retry
在本专栏的前面文章中我们介绍了Spring家族的 重试框架,本篇文章再给大家介绍一个高性能百万级任务重试框架Fast-Retry。它是一个高性能任务重试框架,可以支持百万级别任务的并发重试处理。与Spring-Retry不同,Fast-Retry支持异步任务的重试、超时等待、回调 等功能。
Fast-Retry使用起来也非常简单,可以基于FastRetryBuilder创建一个重试执行器。 也可以和Spring框架结合使用,官方提供了@FastRetry注解可以非常方便的集成到项目中。并且Fast-Retry也可以针对不同的异常或结果进行重试。
对比Spring-Retry和Guava-Retry,Fast-Retry有着绝对的性能优势:
GitHub项目地址:
https://github.com/burukeYou/fast-retry
二、Fast-Retry 实践
添加项目依赖:
<dependency><groupId>io.github.burukeyou</groupId><artifactId>fast-retry-all</artifactId><version>0.2.0</version></dependency>2.1 基于 FastRetryBuilder 的重试
@Slf4j@SpringBootTestpublicclassRetryTest{privateFastRetryer<String>retryer=FastRetryBuilder.builder().attemptMaxTimes(3)// 重试测试.waitRetryTime(2,TimeUnit.SECONDS)// 重试等待时间.retryIfException(true)// 启用异常时重试.retryIfExceptionOfType(TimeoutException.class,RuntimeException.class)// 异常的类型.exceptionRecover(true).build();@Testpublicvoidtest1()throwsExecutionException,InterruptedException{CompletableFuture<String>future=retryer.submit(()->{log.info("开始执行: {}",LocalDateTime.now().toString());inti=1/0;return"success";});log.info("执行结果{}",future.get());}}运行后可以看到重试日志:
2.2 基于 @FastRetry 注解的方式
基于注解的方式,和Spring-Retry一样,首先需要在配置类或启动类上增加@EnableFastRetry注解:
@EnableFastRetrypublicclassRetryDemoApplication{publicstaticvoidmain(String[]args){SpringApplication.run(RetryDemoApplication.class,args);}}创建测试Service,使用@FastRetry注解:
@Slf4j@ServicepublicclassTestService{@FastRetry(maxAttempts=3,retryWait=@RetryWait(delay=2))publicvoidtest(){log.info("开始执行: {}",LocalDateTime.now().toString());inti=1/0;log.info("执行结果succes");}}测试调用:
@Slf4j@SpringBootTestpublicclassRetryTest{@ResourceTestServicetestService;@Testpublicvoidtest2(){testService.test();}}同样可以看到重试日志: