java的spring-retry详解

11f27c61020e433a9c3509b6c7248a41.png

以往我们在进行网络请求的时候,需要考虑网络异常的情况,本文就介绍了利用spring-retry框架进行网络异常重试的基础内容。

35a776c92159bc6356379b621ce659f2.jpeg

提示:以下是本篇文章正文内容,下面案例可供参考

一、spring-retry是什么?

Spring Retry是一个用于在Spring应用程序中实现重试机制的框架。它提供了一种简单的方法来处理那些可能因为短暂的错误(如网络抖动或数据库锁)而失败的操作。

重试机制在很多场景下都是非常有用的。例如,当一个操作因为网络问题或数据库锁而失败时,通常只需要稍作等待,然后再次尝试,就可以成功。而手动实现这样的重试逻辑可能会非常繁琐,并且容易出错。

Spring Retry提供了几个注解和接口,使得在Spring应用程序中实现重试机制变得非常简单。

  1. @Retryable:这个注解可以用于方法上,表示这个方法可能会失败,需要重试。你可以指定重试的次数、延迟时间等参数。

  2. @Recover:这个注解用于定义一个全局的恢复方法,当所有重试都失败后,会调用这个方法。

  3. RetryTemplate:这是一个用于执行重试操作的模板类。你可以使用它来配置重试的策略,如重试次数、延迟时间等。

  4. RetryOperations:这是一个接口,用于定义重试操作的策略。你可以实现这个接口,然后使用RetryTemplate来执行你的重试策略。

总的来说,Spring Retry提供了一种简单而强大的方式来处理那些可能因为短暂错误而失败的操作。它可以帮助你减少手动编写重试逻辑的工作量,提高代码的可维护性。

二、使用步骤

1.引入maven库

代码如下(示例):

<dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>

2. 在spring启动类上开启重试功能

提示:添加@EnableRetry注解开启

@SpringBootApplication
@EnableRetry
public class SpringRetryDemoApplication {
    public static SpringRetryAnnotationService springRetryAnnotationService;
    public static SpringRetryImperativeService springRetryImperativeService;
    public static TranditionalRetryService tranditionalRetryService;


    @Autowired
    public void setSpringRetryAnnotationService(SpringRetryAnnotationService springRetryAnnotationService) {
        SpringRetryDemoApplication.springRetryAnnotationService = springRetryAnnotationService;
    }


    @Autowired
    public void setSpringRetryImperativeService(SpringRetryImperativeService springRetryImperativeService) {
        SpringRetryDemoApplication.springRetryImperativeService = springRetryImperativeService;
    }


    @Autowired
    public void setTranditionalRetryService(TranditionalRetryService tranditionalRetryService) {
        SpringRetryDemoApplication.tranditionalRetryService = tranditionalRetryService;
    }


    public static void main(String[] args) {
        SpringApplication.run(SpringRetryDemoApplication.class, args);
        springRetryAnnotationService.test();
        springRetryImperativeService.test();
        tranditionalRetryService.test();
    }


}

3.公共业务代码

@Service
@Slf4j
public class CommonService {
    public void test(String before) {
        for (int i = 0; i < 10; i++) {
            if (i == 2) {
                log.error("{}:有异常哦,我再试多几次看下还有没异常", before);
                throw new RuntimeException();
            }
            log.info("{}:打印次数: {}", before, i + 1);
        }
    }


    public void recover(String before) {
        log.error("{}:还是有异常,程序有bug哦", before);
    }
}

4. 以往的重试做法

@Service
@Slf4j
public class TranditionalRetryService {
    @Autowired
    CommonService commonService;


    public void test() {
        // 定义重试次数以及重试时间间隔
        int retryCount = 3;
        int retryTimeInterval = 3;
        for (int r = 0; r < retryCount; r++) {
            try {
                commonService.test("以前的做法");
            } catch (RuntimeException e) {
                if (r == retryCount - 1) {
                    commonService.recover("以前的做法");
                    return;
                }
                try {
                    Thread.sleep(retryTimeInterval * 1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }


        }


    }
}

5. 使用spring-retry的命令式编码

5.1 定义重试监听器

提示:监听重试过程的生命周期

@Slf4j
public class MyRetryListener extends RetryListenerSupport {
    @Override
    public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        log.info("监听到重试过程关闭了");
        log.info("=======================================================================");
    }


    @Override
    public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        log.info("监听到重试过程错误了");
    }


    @Override
    public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
        log.info("=======================================================================");
        log.info("监听到重试过程开启了");
        return true;
    }


}

5.2 定义重试配置

提示:配置RetryTemplate重试模板类

@Configuration
public class RetryConfig {
    @Bean
    public RetryTemplate retryTemplate() {
        // 定义简易重试策略,最大重试次数为3次,重试间隔为3s
        RetryTemplate retryTemplate = RetryTemplate.builder()
                .maxAttempts(3)
                .fixedBackoff(3000)
                .retryOn(RuntimeException.class)
                .build();
        retryTemplate.registerListener(new MyRetryListener());
        return retryTemplate;
    }


}

5.3 命令式编码

@Service
@Slf4j
public class SpringRetryImperativeService {
    @Autowired
    RetryTemplate retryTemplate;
    @Autowired
    CommonService commonService;


    public void test() {
        retryTemplate.execute(
                retry -> {
                    commonService.test("命令式");
                    return null;
                },
                recovery -> {
                    commonService.recover("命令式");
                    return null;
                }
        );
    }
}

6 使用spring-retry的注解式编码

@Service
@Slf4j
public class SpringRetryAnnotationService {
    @Autowired
    CommonService commonService;


    /**
     * 如果失败,定义重试3次,重试间隔为3s,指定恢复名称,指定监听器
     */
    @Retryable(value = RuntimeException.class, maxAttempts = 3, backoff = @Backoff(value = 3000L), recover = "testRecover", listeners = {"myRetryListener"})
    public void test() {
        commonService.test("注解式");
    }


    @Recover
    public void testRecover(RuntimeException runtimeException) {
        commonService.recover("注解式");
    }
}

7 启动打印效果

2022-05-06 11:53:12.044  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : =======================================================================
2022-05-06 11:53:12.044  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程开启了
2022-05-06 11:53:12.048  INFO 21812 --- [           main] c.e.s.service.CommonService              : 注解式:打印次数: 1
2022-05-06 11:53:12.048  INFO 21812 --- [           main] c.e.s.service.CommonService              : 注解式:打印次数: 2
2022-05-06 11:53:12.049 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 注解式:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:12.049  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程错误了
2022-05-06 11:53:15.062  INFO 21812 --- [           main] c.e.s.service.CommonService              : 注解式:打印次数: 1
2022-05-06 11:53:15.062  INFO 21812 --- [           main] c.e.s.service.CommonService              : 注解式:打印次数: 2
2022-05-06 11:53:15.062 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 注解式:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:15.062  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程错误了
2022-05-06 11:53:18.065  INFO 21812 --- [           main] c.e.s.service.CommonService              : 注解式:打印次数: 1
2022-05-06 11:53:18.065  INFO 21812 --- [           main] c.e.s.service.CommonService              : 注解式:打印次数: 2
2022-05-06 11:53:18.065 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 注解式:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:18.065  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程错误了
2022-05-06 11:53:18.066 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 注解式:还是有异常,程序有bug哦
2022-05-06 11:53:18.066  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程关闭了
2022-05-06 11:53:18.066  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : =======================================================================
2022-05-06 11:53:18.067  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : =======================================================================
2022-05-06 11:53:18.067  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程开启了
2022-05-06 11:53:18.067  INFO 21812 --- [           main] c.e.s.service.CommonService              : 命令式:打印次数: 1
2022-05-06 11:53:18.067  INFO 21812 --- [           main] c.e.s.service.CommonService              : 命令式:打印次数: 2
2022-05-06 11:53:18.067 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 命令式:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:18.067  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程错误了
2022-05-06 11:53:21.079  INFO 21812 --- [           main] c.e.s.service.CommonService              : 命令式:打印次数: 1
2022-05-06 11:53:21.079  INFO 21812 --- [           main] c.e.s.service.CommonService              : 命令式:打印次数: 2
2022-05-06 11:53:21.079 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 命令式:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:21.079  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程错误了
2022-05-06 11:53:24.082  INFO 21812 --- [           main] c.e.s.service.CommonService              : 命令式:打印次数: 1
2022-05-06 11:53:24.082  INFO 21812 --- [           main] c.e.s.service.CommonService              : 命令式:打印次数: 2
2022-05-06 11:53:24.082 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 命令式:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:24.082  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程错误了
2022-05-06 11:53:24.082 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 命令式:还是有异常,程序有bug哦
2022-05-06 11:53:24.082  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : 监听到重试过程关闭了
2022-05-06 11:53:24.082  INFO 21812 --- [           main] c.e.s.listener.MyRetryListener           : =======================================================================
2022-05-06 11:53:24.082  INFO 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:打印次数: 1
2022-05-06 11:53:24.083  INFO 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:打印次数: 2
2022-05-06 11:53:24.083 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:27.084  INFO 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:打印次数: 1
2022-05-06 11:53:27.084  INFO 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:打印次数: 2
2022-05-06 11:53:27.084 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:30.090  INFO 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:打印次数: 1
2022-05-06 11:53:30.090  INFO 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:打印次数: 2
2022-05-06 11:53:30.090 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:有异常哦,我再试多几次看下还有没异常
2022-05-06 11:53:30.090 ERROR 21812 --- [           main] c.e.s.service.CommonService              : 以前的做法:还是有异常,程序有bug哦

三、总结

本文仅仅简单介绍了spring-retry的基本使用,相较于以往的做法,个人认为注解式更为简便,命令式看个人喜好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值