• 非常非常地重试重试组件,使用杠铃的


    前言

    小伙伴是不是经常遇到接口调用异常的情况?

    很多小伙伴的实现方式是写个循环调用;

    1. "color:#444444">"background-color:#f6f6f6">"color:#333333">for"color:#397300">int i= "color:#880000">1 ;i<= "color:#880000">3 ;i++){
    2. "color:#333333">try {
    3. "color:#333333">if (doExec()){
    4. "color:#333333">break ;
    5. }
    6. }"color:#333333">{
    7. }
    8. }

    方式是比较简单的,但是非常不灵活,今天出门不能很顾虑,但是这种情况很顾虑。实现给大家带来一个重试重试的组件,流行度很明亮,即是番石榴重试组件。功能强大,是平日旅行的必备工具。

    引用

    1. < dependency >
    2. < groupId > com.github.rholder groupId >
    3. < artifactId > guava- retrying< / artifactId >
    4. < version > 2.0.0 version >
    5. -->
    6. -->
    7. 依赖>

    guava-retrying包中应用有相关的guava版本依赖,如果和自身项目突破可以解决。

    示例

    执行方法

    1. @Service public class RetryService {
    2. private static Logger logger = LoggerFactory.getLogger ( RetryService.class )
    3. ; _
    4. 私有AtomicInteger计数= 新AtomicInteger ( 0 );
    5. 公共int doExec(){
    6. logger.info( "调用了{}次" , count .incrementAndGet());
    7. if ( count . get () % 2 == 0 ){
    8. throw new Exception ( "----->异常了哦" );
    9. }
    10. 返回 计数得到();
    11. }
    12. }

    其中定义了doExec方法,每次调用计数加1,如果是的倍数就抛。

    调用方法

    1. 公共字符串 test01(){
    2. Retryer retryer = RetryerBuilder.newBuilder()
    3. .retryIfRuntimeException()
    4. //retryIfResult 表达式返回true,则重试
    5. .retryIfResult(结果 -> {
    6. 如果(结果 % 3 == 0){
    7. logger.info( "----->应该试重了" );
    8. 返回
    9. }
    10. 返回
    11. })
    12. .withStopStrategy(StopStrategies.stopAfterAttempt( 3 ))
    13. 。建造();
    14. 试试{
    15. retryer.call(() -> retryService.doExec());
    16. }捕捉(ExecutionException e){
    17. logger.error( "异常1:{}" ,e.getMessage());
    18. }捕捉(重试异常 e){
    19. logger.error( "异常:{}" ,e.getMessage());
    20. }
    21. 返回 “确定”
    22. }

    从上面代码中,我们就可以实现条件重试。

    番石榴的重试思想可分为重试重条件、停试策略、重试间歇策略

    一、试重条件

    表示在什么情况下,重试。重试组件中的RetryerBuilder的retryIfXXX()方法使用设置在什么情况下进行重试,用户可以在什么情况下根据执行异常进行重试和根据方法执行结果进行重试三个。

    可知异常重试

    1、retryIfException() 当执行方法抛出异常时重试

    2、retryIfRuntimeException()当方法执行抛出异常RuntimeException时重试

    3、retryIfExceptionOfType(exceptionClass)当方法执行抛出异常具体哪个异常时重试

    4、retryIfException(Predicate p)自定义异常什么情况下重试

    可知返回结果重试

    retryIfResult(@Nonnull Predicate resultPredicate)根据返回值判断是否重试。

    1. //返回真时,重试
    2. .retryIfResult(结果 -> {
    3. 如果(结果 % 3 == 0){
    4. logger.info( "----->应该试重了" );
    5. 返回
    6. }
    7. 返回
    8. })

    上面的结果代表的是返回值,判断返回值对3取余,返回真实时则进行重试。

    二、停止重试策略

    重试需要提供停止重试的策略withStopStrategy,简单的方式就是重试次数最多

    1、StopAfterAttempt策略

    从面字上面就知道什么英文,即在执行次数指定次数之后停止重试。

    <span style="color:#444444">#f6f6f6">#880000">.withStopStrategy ( #333333">StopStrategies #880000">.stopAfterAttempt (3))

    2、永不停止策略

    永远重试,一直重试

    <span style="color:#444444">#f6f6f6">#880000">.withStopStrategy ( #333333">StopStrategies #880000">.neverStop ())

    3、StopAfterDelay策略

    设定一个最长的时间;只要设定一次执行最多执行10s,不计次数,试试的时间与第一次的时间差,最长时间,执行则执行,返回执行重试重试异常

    <span style="color:#444444">#f6f6f6">#880000">.withStopStrategy ( #333333">StopStrategies #880000">.stopAfterDelay (10, #333333">TimeUnit #880000">.SECONDS ))

    三、重试间隔策略

    在重试场景中,我们最好的试试重试的间隔,如果没有间隔,可能有连续的重试失败。

    等待策略

    1、固定等待策略

    固定时长重试间歇。

    <span style="color:#444444">#f6f6f6">#880000">.withWaitStrategy ( #333333">WaitStrategies #880000">.fixedWait (1, #333333">TimeUnit #880000">.SECONDS ))

    那就是重试间隔为1秒。

    2、随机等待策略

    随时的间隔时长

    <span style="color:#444444">#f6f6f6">#880000">.withWaitStrategy ( #333333">WaitStrategies #880000">.randomWait (1, #333333">TimeUnit #880000">.SECONDS ,5, #333333">TimeUnit #880000">.SECONDS ))

    第1个间隔时间长,最小个间隔时间长的时间;每次间隔时间是第二个参数。

    3、增量等待策略

    递增的间隔时间长,即每次任务重试的时间递增,越来越长

    <span style="color:#444444">#f6f6f6">#880000">.withWaitStrategy ( #333333">WaitStrategies #880000">.incrementingWait (3, #333333">TimeUnit #880000">.SECONDS ,1, #333333">TimeUnit #880000">.SECONDS ))

    该策略输入一个每隔一段时间的等待时间增加一个步长,然后每次值和时间的长都递增。

    4、异常等待策略

    根据不同的不同,决定不同的间隔时长。

    1. .withWaitStrategy (WaitStrategies.exceptionWait(Exception.class, new Function() {
    2. @Override
    3. public @Nullable Long apply( @Nullable异常输入) {
    4. if (input instanceof NullPointerException){
    5. 返回 1 * 1000升;
    6. }else if (input instanceof IndexOutOfBoundsException){
    7. 返回 2 * 1000升;
    8. }else if (input instanceof IllegalStateException){
    9. 返回 3 * 1000升;
    10. }
    11. 返回0升;
    12. }
    13. }))

    这个的代码一看就知道了。

    是一些常见的策略,不常用的策略,小伙伴们先等待。

    我们需要记录一个非常重要的试试机会关注系统的产品。

    我们来介绍一下重试监听器。

    重试监听器RetryListener

    当重试时,会调用RetryListener的onRetry方法,这样我们就可以做一些自定义的重试的额外任务。

    定义一个类,继承RetryListener接口

    1. 公共 MyRetryListener 实现 RetryListener {
    2. 私有 静态Logger logger = LoggerFactory.getLogger(MyRetryListener.class);
    3. @Override
    4. public void onRetry (Attempt 尝试) {
    5. if (attempt.hasResult()){
    6. logger.info( "===> 方法返回的结果:{}" ,attempt.getResult());
    7. }
    8. if (attempt.hasException()){
    9. logger.info( "===>第{}次执行, 异常:{}" ,attempt.getAttemptNumber(),attempt.getExceptionCause()== null ? "" : attempt.getExceptionCause().getMessage());
    10. 返回
    11. }
    12. logger.info( "===>第{}次执行" ,attempt.getAttemptNumber());
    13. }
    14. }

    在RetryerBuilder中加入;

    .withRetryListener (new MyRetryListener())

    这样就实现了监听业务

    重试原理

    guava-retrying的组件功能还是比较强大的,我们可以看看内核的代码

    1. public V call (Callable callable) throws ExecutionException, RetryException {
    2. long startTime = System.nanoTime();
    3. // 执行次数从
    4. 1Startfor ( int attemptNumber = 1 ; ; attemptNumber++) {
    5. 尝试尝试;
    6. try {
    7. //尝试执行
    8. V result = attemptTimeLimiter. 调用(可调用);
    9. // 执行成功则将结果封装为ResultAttempt
    10. attempt = Retryer.ResultAttempt (result, tryNumberlis(System.nanoTime() - startTime));
    11. } catch
    12. ( Thrable t) { // 执行异常则将封装结果为ExceptionAttempt
    13. }
    14. // 这里将执行结果传给RetryListener 做一些额外的事情
    15. for (RetryListener listener : listeners) {
    16. listener.onRetry(尝试);
    17. }
    18. //这个就是决定是否要进行重试的地方,如果不进行重试直接返回结果,执行成功就返回结果,执行失败就返回异常
    19. if (!rejectionPredicate.apply(attempt)) {
    20. return attempt.get() ;
    21. }
    22. // 到这里,说明需要重试,此时先决定是否达到异常则停止重试的时机,如果了则直接返回
    23. if (stopStrategy.shouldStop(attempt)) {
    24. throw new RetryException(attemptNumber, attempt) ;
    25. } else {
    26. // 决定重试间隔
    27. long sleepTime = waitStrategy.computeSleepTime(attempt);
    28. 尝试{
    29. // 进行阻尼
    30. blockStrategy.block(sleepTime);
    31. }捕捉(InterruptedException e){
    32. Thread.currentThread().interrupt();
    33. 抛出 的重试异常(尝试编号,尝试);
    34. }
    35. }
    36. }
    37. }
  • 相关阅读:
    使用MLC-LLM将RWKV 3B模型跑在Android手机上
    leetcode 409 Longest Palindrome 最长回文串(简单)
    Spring Boot——Thymeleaf
    [Spring MVC 8]高并发实战小Demo
    PostgreSQL按月计算每天值的累加
    【接口测试】Postman(一)--接口测试知识准备
    vscode更改为中文版本
    (附源码)ssm高校选课系统 毕业设计 291627
    【STM32】FSMC—扩展外部 SRAM 初步使用 1
    第四章:Python中的字典(下)
  • 原文地址:https://blog.csdn.net/Candyz7/article/details/126948433