spring-retry实现方法请求重试

简介: spring-retry实现方法请求重试

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.2 公共业务代码

@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.3 传统的重试做法

@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.4 使用spring-retry的命令式编码

2.4.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.4.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.4.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.5 使用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)该方法的返回值类型与重试方法保持一致

再次测试如下(发现不会再抛出异常):

目录
相关文章
|
12天前
|
缓存 安全 Java
《深入理解Spring》过滤器(Filter)——Web请求的第一道防线
Servlet过滤器是Java Web核心组件,可在请求进入容器时进行预处理与响应后处理,适用于日志、认证、安全、跨域等全局性功能,具有比Spring拦截器更早的执行时机和更广的覆盖范围。
|
12天前
|
缓存 监控 Java
《深入理解Spring》拦截器(Interceptor)——请求处理的艺术
Spring拦截器是Web开发中实现横切关注点的核心组件,基于AOP思想,可在请求处理前后执行日志记录、身份验证、权限控制等通用逻辑。相比Servlet过滤器,拦截器更贴近Spring容器,能访问Bean和上下文,适用于Controller级精细控制。通过实现`HandlerInterceptor`接口的`preHandle`、`postHandle`和`afterCompletion`方法,可灵活控制请求流程。结合配置类注册并设置路径匹配与执行顺序,实现高效复用与维护。常用于认证鉴权、性能监控、统一异常处理等场景,提升应用安全性与可维护性。
消息中间件 Java Kafka
131 0
|
1月前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
187 1
使用Spring的@Retryable注解进行自动重试
|
3月前
|
JSON 前端开发 Java
Spring MVC 核心组件与请求处理机制详解
本文解析了 Spring MVC 的核心组件及请求流程,核心组件包括 DispatcherServlet(中央调度)、HandlerMapping(URL 匹配处理器)、HandlerAdapter(执行处理器)、Handler(业务方法)、ViewResolver(视图解析),其中仅 Handler 需开发者实现。 详细描述了请求执行的 7 步流程:请求到达 DispatcherServlet 后,经映射器、适配器找到并执行处理器,再通过视图解析器渲染视图(前后端分离下视图解析可省略)。 介绍了拦截器的使用(实现 HandlerInterceptor 接口 + 配置类)及与过滤器的区别
259 0
|
6月前
|
缓存 安全 Java
深入解析HTTP请求方法:Spring Boot实战与最佳实践
这篇博客结合了HTTP规范、Spring Boot实现和实际工程经验,通过代码示例、对比表格和架构图等方式,系统性地讲解了不同HTTP方法的应用场景和最佳实践。
614 5
|
6月前
|
Java Spring 容器
两种Spring Boot 项目启动自动执行方法的实现方式
在Spring Boot项目启动后执行特定代码的实际应用场景中,可通过实现`ApplicationRunner`或`CommandLineRunner`接口完成初始化操作,如系统常量或配置加载。两者均支持通过`@Order`注解控制执行顺序,值越小优先级越高。区别在于参数接收方式:`CommandLineRunner`使用字符串数组,而`ApplicationRunner`采用`ApplicationArguments`对象。注意,`@Order`仅影响Bean执行顺序,不影响加载顺序。
520 2
|
8月前
|
人工智能 自然语言处理 Java
Spring 集成 DeepSeek 的 3大方法(史上最全)
DeepSeek 的 API 接口和 OpenAI 是兼容的。我们可以自定义 http client,按照 OpenAI 的rest 接口格式,去访问 DeepSeek。自定义 Client 集成DeepSeek ,可以通过以下步骤实现。步骤 1:准备工作访问 DeepSeek 的开发者平台,注册并获取 API 密钥。DeepSeek 提供了与 OpenAI 兼容的 API 端点(例如),确保你已获取正确的 API 地址。
Spring 集成 DeepSeek 的 3大方法(史上最全)
|
10月前
|
Java Spring
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
351 73
|
11月前
|
前端开发 Java 开发者
Spring MVC中的请求映射:@RequestMapping注解深度解析
在Spring MVC框架中,`@RequestMapping`注解是实现请求映射的关键,它将HTTP请求映射到相应的处理器方法上。本文将深入探讨`@RequestMapping`注解的工作原理、使用方法以及最佳实践,为开发者提供一份详尽的技术干货。
1058 2

热门文章

最新文章