移动应用网站开发阶段作业,深圳西乡 网站建设,网站建设综合,上海远丰电商网站建设公司怎么样#x1f604; 19年之后由于某些原因断更了三年#xff0c;23年重新扬帆起航#xff0c;推出更多优质博文#xff0c;希望大家多多支持#xff5e; #x1f337; 古之立大事者#xff0c;不惟有超世之才#xff0c;亦必有坚忍不拔之志 #x1f390; 个人CSND主页——Mi… 19年之后由于某些原因断更了三年23年重新扬帆起航推出更多优质博文希望大家多多支持 古之立大事者不惟有超世之才亦必有坚忍不拔之志 个人CSND主页——Micro麦可乐的博客 《Docker实操教程》专栏以最新的Centos版本为基础进行Docker实操教程入门到实战 《RabbitMQ》专栏主要介绍使用JAVA开发RabbitMQ的系列教程从基础知识到项目实战 《设计模式》专栏以实际的生活场景为案例进行讲解让大家对设计模式有一个更清晰的理解 《Jenkins实战》专栏主要介绍JenkinsDocker的实战教程让你快速掌握项目CI/CD是2024年最新的实战教程 《Spring Boot》专栏主要介绍我们日常工作项目中经常应用到的功能以及技巧代码样例完整 如果文章能够给大家带来一定的帮助欢迎关注、评论互动 Spring Boot集成 Spring Retry 实现容错重试机制 1、前言2、什么是 Spring Retry3、开始简单集成4、Spring Retry的高级配置❶ 自定义重试策略canRetry方法的介绍open方法的介绍close方法的介绍registerThrowable方法的介绍 ❷ 使用 RetryTemplate 5、代码汇总6、总结 1、前言
本文对应源码下载地址 https://download.csdn.net/download/lhmyy521125/89430153 无需积分
在日常开发过程中我们经常会与第三方接口进行交互例如短信发送、远程服务调用、争抢锁等场景当正常调用发生异常时例如网络延迟、服务宕机或临时故障等问题会导致本次请求交互失败而借助 Spring Retry 能够帮助我们在方法调用失败时自动重试从而提高系统的稳定性和健壮性。
本文跟着博主由浅入深一起来学习 Spring Retry
2、什么是 Spring Retry
Spring Retry 是一个用于简化 Java 方法重试逻辑的库它能够在方法调用失败时自动重试并提供了丰富的配置选项支持重试次数、重试间隔时间、异常类型等配置。通过使用 Spring Retry可以方便地在 Spring Boot 应用中实现容错和重试机制。 Spring Retry 的特性 自动重试当方法调用失败时根据配置的重试策略自动重试支持多种异常类型可以配置在遇到特定异常时重试如 IOException、SQLException 等重试间隔控制支持配置重试间隔时间可以设置固定间隔或指数增长间隔自定义重试策略提供了灵活的重试策略接口可以实现自定义的重试逻辑 3、开始简单集成
构建你的 Spring Boot 项目在pom.xml中引入依赖
dependencygroupIdorg.springframework.retry/groupIdartifactIdspring-retry/artifactId
/dependency
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-aop/artifactId
/dependency配置 Spring Retry 可以通过注解或配置文件进行配置。下面展示如何使用注解方式配置
使用EnableRetry注解开启 在主类 或对应配置类上加EnableRetry注解表示启用重试机制
SpringBootApplication
EnableRetry
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}使用 Retryable 注解 Retryable 注解是 Spring Retry 的核心注解用于标记需要重试的方法。示例代码如下
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;Service
public class RetryService {//初始化重试次数private int attempt 0;Retryable(value {RuntimeException.class}, maxAttempts 5, backoff Backoff(delay 2000))public String retryMethod() {attempt;System.out.println(重试次数Attempt: attempt);if (attempt 3) {throw new RuntimeException(出现故障, 重试中...);}return Success!;}
}配置参数说明 value 指定了需要重试的异常类型这里是 RuntimeException maxAttempts 设置了最大重试次数这里是 5 次 backoff 设置了重试间隔使用 Backoff 注解指定延迟时间单位是毫秒这里是 2000 毫秒2秒 创建一个controller用于调用重试方法并测试重试逻辑
import com.example.demo.service.RetryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;RestControllerpublic class RetryController {Autowiredprivate RetryService retryService;GetMapping(/retry)public String retry() {try {return retryService.retryMethod();} catch (Exception e) {return 重试失败: e.getMessage();}}
}接口请求测试
观察控制台 测试你会发现接口请求过程中控制台一直输出了三次重试次数后成功返回你以为Spring Retry 就这么点东西我们继续往下看
4、Spring Retry的高级配置
❶ 自定义重试策略
在某些情况下默认的重试策略可能无法满足需求这时可以通过实现 RetryPolicy 接口来自定义重试策略控制重试的逻辑和条件
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryPolicy;public class CustomRetryPolicy implements RetryPolicy {private static final int MAX_RETRIES 3;Overridepublic boolean canRetry(RetryContext context) {// 检查重试次数int retryCount context.getRetryCount();if (retryCount MAX_RETRIES) {return false; // 如果重试次数达到最大值不再重试}// 检查异常类型Throwable lastException context.getLastThrowable();if (lastException instanceof MyCustomException) {// 如果是我们关心的特定异常类型允许重试return true;}// 其他情况下不允许重试return false;}//MyCustomException 是你定义的异常类型public class MyCustomException extends Exception { /* ... */ }//在重试操作开始时创建新的上下文对象用于存储重试信息Overridepublic RetryContext open(RetryContext retryContext) {return null;}//在重试操作结束时执行清理或记录操作Overridepublic void close(RetryContext retryContext) {}//在重试过程中遇到异常时记录异常信息Overridepublic void registerThrowable(RetryContext retryContext, Throwable throwable) {}
}canRetry方法的介绍
boolean canRetry(RetryContext context);canRetry 方法是重试策略的核心逻辑通过检查当前的重试上下文信息决定是否可以继续进行重试。通常会根据重试次数、异常类型等条件来判断是否继续重试 作用判断是否应该继续进行重试操作 参数RetryContext context表示当前的重试上下文包含了重试次数、上次异常等信息 返回值boolean返回 true 表示可以继续重试返回 false 表示停止重试 open方法的介绍
RetryContext open(RetryContext parent);在重试操作开始时Spring Retry 会调用 open 方法创建一个新的 RetryContext这个上下文对象会在整个重试过程中传递用于存储重试相关的信息 作用创建并返回一个新的 RetryContext 对象表示一次新的重试操作的上下文信息 参数RetryContext parent表示父级上下文如果没有父级上下文则为 null 返回值RetryContext表示新的重试上下文 close方法的介绍
当重试操作完成后无论是否成功Spring Retry 都会调用 close 方法可以在这个方法中执行一些清理操作或记录日志
void close(RetryContext context);作用在重试操作完成时无论成功或失败调用用于清理或记录重试操作的结束 参数RetryContext context表示当前的重试上下文 registerThrowable方法的介绍
void registerThrowable(RetryContext context, Throwable throwable);在重试过程中如果遇到异常Spring Retry 会调用 registerThrowable 方法将异常信息记录到 RetryContext 中。这个信息可以在后续的重试操作中使用 作用在重试过程中遇到异常时调用用于记录当前的异常信息 参数RetryContext context表示当前的重试上下文 参数Throwable throwable表示当前遇到的异常 在Spring配置中使用自定义 RetryPolicy 同时也可以配置定制 RetryTemplate
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;Configuration
public class RetryConfig {Beanpublic RetryTemplate retryTemplate() {RetryTemplate retryTemplate new RetryTemplate();// 设置自定义的RetryPolicyCustomRetryPolicy retryPolicy new CustomRetryPolicy(5);// 还可以设置其他的策略如BackoffPolicy等 FixedBackOffPolicy backOffPolicy new FixedBackOffPolicy();backOffPolicy.setBackOffPeriod(2000);retryTemplate.setRetryPolicy(retryPolicy);retryTemplate.setBackOffPolicy(backOffPolicy);return retryTemplate;}
}❷ 使用 RetryTemplate
RetryTemplate 是 Spring Retry 提供的一个模板类允许我们更细粒度地控制重试逻辑。下面是使用 RetryTemplate 的例子
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;Service
public class TemplateRetryService {private final RetryTemplate retryTemplate;public TemplateRetryService(RetryTemplate retryTemplate) {this.retryTemplate retryTemplate;}public String executeWithRetry() {return retryTemplate.execute(context - {System.out.println(TemplateRetryService执行重试..);if (Math.random() 0.7) {throw new RuntimeException(重试失败);}return Success!;});}
}5、代码汇总
Spring Retry 也是可以与 Spring AOP 配合使用通过切面拦截方法调用实现全局的重试逻辑只需要创建一个切面即可
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;Aspect
Component
public class RetryAspect {Before(annotation(org.springframework.retry.annotation.Retryable))public void beforeRetry() {System.out.println(执行重试前...);//比如记录请求发起的时间等}
}讲解了这么多我们还是把代码汇总一下进行一次演示编写一个Controller用来测试两个重试服务
RestController
RequestMapping(/api)
public class RetryController {Autowiredprivate RetryService retryService;Autowiredprivate TemplateRetryService templateRetryService;GetMapping(/retry)public String retry() {try {return retryService.retryMethod();} catch (Exception e) {return 重试失败: e.getMessage();}}GetMapping(/template-retry)public String templateRetry() {return templateRetryService.executeWithRetry();}
}最终代码结构如下目的只是为了演示忽略都在一个包中 再次运行测试分别测试 /api/retry 接口以及模板重试服务的接口 /api/template-retry结果如下 OK至此 Spring Retry 的介绍以及使用已经讲完了小伙伴们可以根据代码片段自行定制自己的重试策略
6、总结
Spring Retry 是一个强大的工具能够帮助我们在系统出现临时故障时自动重试提高系统的稳定性和健壮性。在实际开发中根据具体的业务需求和系统情况合理配置和使用 Spring Retry可以显著提升系统的可靠性。
本文的代码主要是演示使用小伙伴们可以根据自己业务需求进行修改升级。如果本文对您有所帮助希望 一键三连 给博主一点点鼓励如果您有任何疑问或建议请随时留言讨论