重学SpringBoot3-Spring Retry实践

ops/2025/2/24 20:35:55/

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》
期待您的点赞??收藏评论

重学SpringBoot3-Spring Retry实践
  • 1. 简介
  • 2. 环境准备
  • 3. 使用方式
    • 3.1 注解方式
      • 基础使用
      • 自定义重试策略
      • 失败恢复机制
      • 重试和失败恢复效果
      • 注意事项
    • 3.2 编程式使用
    • 3.3 监听重试过程
      • 监听重试效果
  • 4. 最佳实践
  • 5. 总结

1. 简介

Spring Retry是Spring生态系统中的一个重要组件,它提供了自动重试失败操作的能力。在分布式系统中,由于网络抖动、服务暂时不可用等临时性故障,重试机制显得尤为重要。本文将详细介绍如何在 SpringBoot 3 应用中集成和使用 Spring Retry。

2. 环境准备

首先在 SpringBoot 3 项目中添加必要的依赖:

<dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId><version>2.0.5</version>
</dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>6.1.13</version>
</dependency>

在启动类或配置类上添加 @EnableRetry 注解以启用重试功能:

@SpringBootApplication
@EnableRetry
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

3. 使用方式

3.1 注解方式

基础使用

最简单的使用方式是通过 @Retryable 注解:

@Service
public class UserService {@Retryablepublic void riskyOperation() {// 可能失败的操作}
}
自定义重试策略

可以通过 @Retryable 注解的参数来自定义重试行为:

@Service
@Slf4j
public class EmailServiceImpl implements IEmailService {@Resourceprivate JavaMailSender mailSender;@Value("${spring.mail.username}")private String from;/*** 发送简单文本邮件** @param to* @param subject* @param text*/@Override@Retryable(retryFor = MailSendException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))public void sendSimpleEmail(String to, String subject, String text) {try {SimpleMailMessage message = new SimpleMailMessage();message.setFrom(from);message.setTo(to);message.setSubject(subject);message.setText(text);mailSender.send(message);log.info("Simple email sent successfully to: {}", to);} catch (Exception e) {log.error("Failed to send simple email", e);throw new MailSendException("Failed to send email", e);}}
}

当执行发生指定异常,将会尝试进行重试,一旦达到最大尝试次数,但仍有异常发生,就会抛出 ExhaustedRetryException。重试最多可进行三次,两次重试之间的延迟时间默认为一秒。

失败恢复机制

使用 @Recover 注解定义重试失败后的恢复方法:

    /*** 发送简单文本邮件** @param to* @param subject* @param text*/@Override@Retryable(retryFor = MailSendException.class, // 指定异常类型maxAttempts = 3, // 最大重试次数backoff = @Backoff(delay = 1000) // 指定退避策略,例如延迟时间)public void sendSimpleEmail(String to, String subject, String text) {try {SimpleMailMessage message = new SimpleMailMessage();message.setFrom(from);message.setTo(to);message.setSubject(subject);message.setText(text);mailSender.send(message);log.info("Simple email sent successfully to: {}", to);} catch (Exception e) {log.error("Failed to send simple email", e.getMessage());throw new MailSendException("Failed to send email", e);}}@Recoverpublic void recover(MailSendException e, String param) {// 处理最终失败的情况log.error("Final recovery : {}", param);}
重试和失败恢复效果

重试和失败恢复效果

注意事项

注意@Recover 失效的情况:

  • @Recover 方法的参数类型与实际异常不匹配;
  • @Recover 方法的返回类型与 @Retryable 方法不一致;
  • @Recover 方法的其他参数与 @Retryable 方法参数不匹配。

3.2 编程式使用

除了注解方式,Spring Retry 还提供了 RetryTemplate 用于编程式重试:

@Configuration
public class RetryConfig {@Beanpublic RetryTemplate retryTemplate() {RetryTemplate template = new RetryTemplate();// 配置重试策略SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();retryPolicy.setMaxAttempts(3);// 配置退避策略FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();backOffPolicy.setBackOffPeriod(1000L);template.setRetryPolicy(retryPolicy);template.setBackOffPolicy(backOffPolicy);return template;}
}

使用RetryTemplate:

@Service
public class UserService {@Autowiredprivate RetryTemplate retryTemplate;public void executeWithRetry() {retryTemplate.execute(context -> {// 需要重试的业务逻辑return null;});}
}

3.3 监听重试过程

通过实现RetryListener接口,可以监听重试的整个生命周期:

public class CustomRetryListener extends RetryListenerSupport {@Overridepublic <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {// 记录错误日志log.error("Retry error occurred", throwable);}@Overridepublic <T, E extends Throwable> void close(RetryContext context,RetryCallback<T, E> callback, Throwable throwable) {// 重试结束时的处理log.info("Retry completed");}
}

将监听器注册到RetryTemplate:

@Configuration
public class RetryConfig {@Beanpublic RetryTemplate retryTemplate() {RetryTemplate template = new RetryTemplate();// ... 其他配置 ...template.registerListener(new CustomRetryListener());return template;}
}
监听重试效果

监听重试过程

4. 最佳实践

  1. 明确重试场景:只对临时性故障使用重试机制,对于业务错误或永久性故障应直接失败。

  2. 设置合理的重试次数:通常3-5次即可,过多的重试可能会加重系统负担。

  3. 使用退避策略:建议使用指数退避策略(ExponentialBackOffPolicy),避免立即重试对系统造成冲击。

  4. 添加监控和日志:通过RetryListener记录重试情况,便于问题排查。

  5. 设置超时时间:避免重试过程持续时间过长。

5. 总结

Spring Retry为Spring应用提供了强大而灵活的重试机制,既可以通过注解优雅地实现重试,也可以使用RetryTemplate进行更细粒度的控制。在实际应用中,合理使用重试机制可以提高系统的健壮性和可用性。

需要注意的是,重试机制并非万能药,在使用时要根据具体场景选择合适的重试策略,并做好监控和告警,以便及时发现和处理问题。


http://www.ppmy.cn/ops/161040.html

相关文章

计算机毕业设计SpringBoot+Vue.jst0甘肃非物质文化网站(源码+LW文档+PPT+讲解)

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…

go json处理 encoding/json 查询和修改gjson/sjson

推荐 标准库encoding/json import ("encoding/json""log" )// Student1 注意点&#xff1a; // 1. 注意alain别名的写法&#xff1a; json:"name1" 而非 "json:name1" // 2. 注意json.Marshal的时候只输出首字母大写的属性 // 3. jso…

机器视觉--Halcon的数据结构(数组)

引言 在机器视觉领域&#xff0c;Halcon 作为一款功能强大且广泛应用的软件&#xff0c;其丰富的数据结构为开发者提供了高效处理各种视觉任务的能力。数组作为其中一种基础且重要的数据结构&#xff0c;在 Halcon 中扮演着不可或缺的角色。它能够有序地存储多个相同类型的数据…

鸿蒙NEXT应用App测试-通用测试

注意&#xff1a;大家记得学完通用测试记得再学鸿蒙专项测试 https://blog.csdn.net/weixin_51166786/article/details/145768653 注意&#xff1a;博主有个鸿蒙专栏&#xff0c;里面从上到下有关于鸿蒙next的教学文档&#xff0c;大家感兴趣可以学习下 如果大家觉得博主文章…

体验用ai做了个python小游戏

体验用ai做了个python小游戏 写在前面使用的工具2.增加功能1.要求增加视频作为背景。2.我让增加了一个欢迎页面。3.我发现中文显示有问题。4.我提出了背景修改意见&#xff0c;欢迎页面和结束页面背景是视频&#xff0c;游戏页面背景是静态图片。5.提出增加更多游戏元素。 总结…

安全面试3

文章目录 一个单位的一级域名可能不止一个&#xff0c;怎么收集某个单位的所有域名&#xff0c;注意不是子域名用转义字符防御时&#xff0c;如果遇到数据库的列名或是表名本身就带着特殊字符&#xff0c;应该怎么做宽字节注入原理防御宽字节注入的方法 基于黑白名单的修复&…

C++ 设计模式-访问者模式

C++访问者模式 一、模式痛点:当if-else成为维护噩梦 开发动物园管理系统,最初的需求很简单: class Animal {}; class Cat : public Animal {}; class Dog : public Animal {};// 处理动物叫声 void makeSound(Animal* a) {if (auto c = dynamic_cast<Cat*>(a)) {st…

火语言RPA--Excel插入空列

【组件功能】&#xff1a;在Excel内指定的位置插入空列 配置预览 配置说明 在第n列之前 支持T或# 填写插入添加插入第n列之前列名&#xff0c;列名从A开始&#xff0c;依次递增。 插入n列 支持T或# 插入多少列。 Sheet页名称 支持T或# Excel表格工作簿名称。 示例 Exc…