spring retry实现方法请求重试的使用步骤
作者:赵广陆 发布时间:2021-12-31 15:11:11
1 spring-retry是什么?
以往我们在进行网络请求的时候,需要考虑网络异常的情况,本文就介绍了利用spring-retry,是spring提供的一个重试框架,原本自己实现的重试机制,现在spring帮封装好提供更加好的编码体验。
2 使用步骤
2.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.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();
}
}
2.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);
}
}
2.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();
}
}
}
}
}
2.5 使用spring-retry的命令式编码
2.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;
}
}
2.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;
}
}
2.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;
}
);
}
}
2.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("注解式");
}
}
3 SpringBoot整合spring-retry
我们使用SpringBoot来整合spring-retry组件实现重试机制。
3.1 添加@EnableRetry注解
在主启动类Application上添加@EnableRetry注解,实现对重试机制的支持
@SpringBootApplication
@EnableRetry
public class RetryApplication {
public static void main(String[] args) {
SpringApplication.run(RetryApplication.class, args);
}
}
注意:@EnableRetry也可以使用在配置类、ServiceImpl类、方法上
3.2 接口实现
注意:接口类一定不能少,在接口类中定义你需要实现重试的方法,否则可能会无法实现重试功能
我的测试接口类如下:
public interface RetryService { public String testRetry() throws Exception;}
3.3 添加@Retryable注解
我们针对需要实现重试的方法上添加@Retryable
注解,使该方法可以实现重试,这里我列出ServiceImpl
中的一个方法:
@Service
public class RetryServiceImpl implements RetryService {
@Override
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000,multiplier = 1.5))
public String testRetry() throws Exception {
System.out.println("开始执行代码:"+ LocalTime.now());
int code = 0;
// 模拟一直失败
if(code == 0){
// 这里可以使自定义异常,@Retryable中value需与其一致
throw new Exception("代码执行异常");
}
System.out.println("代码执行成功");
return "success";
}
}
说明:@Retryable配置元数据情况:
value :针对指定抛出的异常类型,进行重试,这里指定的是Exception
maxAttempts :配置最大重试次数,这里配置为3次(包含第一次和最后一次)
delay: 第一次重试延迟间隔,这里配置的是2s
multiplier :每次重试时间间隔是前一次几倍,这里是1.5倍
3.4 Controller测试代码
@RestController
@RequestMapping("/test")
public class TestController {
// 一定要注入接口,通过接口去调用方法
@Autowired
private RetryService retryService;
@GetMapping("/retry")
public String testRetry() throws Exception {
return retryService.testRetry();
}
}
3.5 发送请求
发送请求后,我们发现后台打印情况,确实重试了3次,并且在最后一次重试失败的情况下,才抛出异常,具体如下(可以注意下时间间隔)
3.6 补充:@Recover
一般情况下,我们重试最大设置的次数后,仍然失败抛出异常,我们会通过全局异常处理类进行统一处理,但是我们其实也可以自行处理,可以通过@Recover
注解来实现,具体如下:
@Service
public class RetryServiceImpl implements RetryService {
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000,multiplier = 1.5))
public String testRetry() throws Exception {
System.out.println("开始执行代码:"+ LocalTime.now());
int code = 0;
if(code == 0){
// 这里可以使自定义异常,@Retryable中value需与其一致
throw new Exception("代码执行异常");
}
System.out.println("代码执行成功");
return "success";
}
/**
* 最终重试失败处理
* @param e
* @return
*/
@Recover
public String recover(Exception e){
System.out.println("代码执行重试后依旧失败");
return "fail";
}
}
注意:
1)@Recover的方法中的参数异常类型需要与重试方法中一致
2)该方法的返回值类型与重试方法保持一致
再次测试如下(发现不会再抛出异常)
来源:https://blog.csdn.net/ZGL_cyy/article/details/125668526


猜你喜欢
- c++回调之利用函数指针示例#include <iostream>using namespace std;/**********
- 本文实例讲述了Android基于API的Tabs3实现仿优酷tabhost效果。分享给大家供大家参考,具体如下:前两天老师就让自己写个视频播
- 微服务通过Feign调用进行密码安全认证在项目中,微服务之间的通信也是通过Feign代理的HTTP客户端通信,为了保护我们的业务微服务不被其
- 最近在用SpringMvc写项目的时候,遇到一个问题,就是方法的鉴权问题,这个问题弄了一天了终于解决了,下面看下解决方法项目需求:需要鉴权的
- POST接口formdata传参模板记录var res = ""; HttpClient _httpClient = n
- 只要是面向对象的编程语言,基本上都有类Class的用法,只是好不好用,好不好记而已,面向对象是c++开始引入的,但是c++ 关于类的东西,弄
- 前言在计算机操作系统中,进程是进行资源分配和调度的基本单位。这对于基于Linux内核的Android系统也不例外。在Android的设计中,
- 做快递面单打印模板,快递要求纸张大小100 x 150mm。PageSize.A4=595 x 842A4尺寸=210mm×297mm故设置
- 一、LINQ的体系结构语言集成查询 (LINQ) (C#) | Microsoft 官方文档LINQ总共包括五个部分: 程序集命名
- RestTemplate第一次请求响应速度较慢问题使用RestTemplate请求微信的接口发现第一次请求需要8秒左右的时间,查阅了JDK资
- 一、概述针对八种基本数据类型定义相应的引用类型—包装类(封装类)。二、作用有了类的特点,就可以调用类中的方法,Java才
- 一、简介项目开发中存在系统之间互调问题,又不想用dubbo,这里提供几种springboot方案:1、使用Feign进行消费(推荐)2、使用
- 简介一般情况下我们在flutter中搭建的app基本上都是用的是MaterialApp这种设计模式,MaterialApp中为我们接下来使用
- 目录实现多线程的三种方式一、继承Thread类二、实现Runnable接口三、实现Callable和Future接口多线程单条数据事务管理今
- 1. 你知道线程安全问题吗?线程安全问题:一般指在多线程模式下,多个线程对同一个共享数据进行操作时,第一个线程还没来得及更新共享数据,从而导
- @Transactional是我们在用Spring时候几乎逃不掉的一个注解,该注解主要用来声明事务。它的实现原理是通过Spring AOP在
- 本文实例讲述了Java设计模式之模板方法模式。分享给大家供大家参考,具体如下:我们在生活中,很多事情都包含特定的一些步骤。如去银行办理业务,
- C#操作注册表全攻略相信每个人对注册表并不陌生,在运行里面输入“regedit”就可以打开注册表编辑器了。这东西对Windows系统来说可是
- 这里不准备讨论REST的细节内容,但是总体上,REST是让客户端与服务器段的交互通过发送和接收展示资源的方式来进行,在这里有必要说明:Fie
- eclipse中改变默然的workspace的方法可以有以下几种:1.在创建project的时候,手动选择使用新的workspace,如创建