spring-retry对第三方接口做重试,和处理操作
-
-
-
org.springframework.retry -
spring-retry -
-
-
-
-
org.springframework -
spring-aop -
5.3.29 -
-
-
-
org.springframework -
spring-aspects -
5.3.29 -
- @RestController
- @RequestMapping("/test")
- public class TestController {
-
-
- /**
- * 在需要重试的接口上添加@Retryable注解,并指定重试策略
- * value = Exception.class 表示重试的异常类型
- * maxAttempts = 3 表示重试次数
- * backoff = @Backoff(delay = 1000,multiplier = 1.5) 表示重试间隔时间 其默认间隔时间为1秒
- * multiplier = 1.5 表示间隔时间的倍数 延迟的倍数
- * @param code
- * @return
- * @throws Exception
- */
- @GetMapping("/get/{code}")
- @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000,multiplier = 1.5))
- public String get(@PathVariable Integer code) throws Exception {
-
-
- System.out.println("code = " + System.currentTimeMillis());
- if (code == 1){
- throw new Exception("get重试");
- }
- return "get正常" + System.currentTimeMillis();
- }
-
- /**
- * 重试次数用完 还是失败的话
- * 就会进入recover方法
- * 对于@Recover注解的方法 方法的返回值要和Retryable注解的方法的返回值保持一致
- * 异常也要和重试发生的异常类型一致
- * 该回调方法与重试方法要写在一个实现类里面
- * @param e
- * @param code
- * @return
- */
- @Recover
- public String recover(Exception e,Integer code){
- return "重试后进入的方法 可以拿到异常和参数";
- }
-
- }
想要使用重试功能 要在启动类上开启该功能
- @SpringBootApplication
- @EnableRetry //开启重试功能
- public class SpringRetryApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpringRetryApplication.class, args);
- }
-
- }
大致的工作流程是 如果请求的实现里面出现了指定的异常 就会自动重试再次执行该方法
如果在你设置的重试次数之后 还有错误 那就是第三方接口的问他 需要在回调方法里面记录下异常
或者联系第三方接口的提供者处理该异常