吉安好的网站建设公司,网页设计工程师工资,cn后缀做网站,石家庄网站制作长沙文章目录 使用背景spring-retry介绍快速使用加入依赖开启Retry使用参数 使用背景
在有些特定场景#xff0c;如和第三方对接。 我们调用接口时需要支持重试功能#xff0c;第一次调用没成功#xff0c;我们需要等待x秒后再次调用。 通常会设置重试次数#xff0c;避免业务… 文章目录 使用背景spring-retry介绍快速使用加入依赖开启Retry使用参数 使用背景
在有些特定场景如和第三方对接。 我们调用接口时需要支持重试功能第一次调用没成功我们需要等待x秒后再次调用。 通常会设置重试次数避免业务。 一般我们会这样写
public ApiResponseBoolean test() {//模拟调用System.out.println(开始调用第 num 次);//业务逻辑boolean result false;if (result) {System.out.println(执行完成);} else if (num totalNum) {System.out.println(重试结束);num 1;} else {System.out.println(重试);num;test();}return ApiResponse.ok(true);
}这样写本身没什么问题。 但是如果多个接口都需要重试的话代码就不优雅了。
spring-retry介绍
spring系列的spring-retry是另一个实用程序模块 可以帮助我们以标准方式处理任何特定操作的重试。 在spring-retry中所有配置都是基于简单注释的。
快速使用
加入依赖
dependencygroupIdorg.springframework.retry/groupIdartifactIdspring-retry/artifactId
/dependency
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-aop/artifactId
/dependency开启Retry
启动上增加注解EnableRetry
EnableRetry使用
GetMapping(test)
Retryable(value Exception.class,maxAttempts 5,backoff Backoff(delay 2000,multiplier 1.5))
public ApiResponseBoolean test() {System.out.println(开始调用第 num 次);boolean result false;if (!result){num;throw new BizException(调用失败需要重试);}System.out.println(执行完成);return ApiResponse.ok(true);
}参数
value抛出指定异常才会重试 include和value一样默认为空当exclude也为空时默认所有异常 exclude指定不处理的异常 maxAttempts最大重试次数默认5次 backoff重试等待策略默认使用BackoffBackoff的value默认为1000L我们设置为2000Lmultiplier指定延迟倍数默认为0表示固定暂停1秒后进行重试如果把multiplier设置为1.5则第一次重试为2秒第二次为3秒第三次为4.5秒。