一.概述
二.快速入门
1.导依赖
<!--retry的依赖-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
2.在启动类上加@EnableRetry注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.EnableRetry;
@EnableRetry//加上这个注解
@SpringBootApplication(scanBasePackages="com.guguo")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
3.测试代码
package com.guguo.controller;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("")
@Api(tags = "测试重试")
public class RetryController {
/**
* @Retryable 参数说明
* value:抛出指定异常才会重试
* maxAttempts:最大重试次数,默认3次
* backoff:重试等待策略
* recover:执行回调方法名称
*/
@GetMapping("retryable")
@SneakyThrows(Exception.class)
@Retryable(value = RetryException.class, maxAttempts = 2,
backoff = @Backoff(delay = 1000, multiplier = 2), recover = "recover")//第一次等1秒,第二次等2秒,第三次等4秒
public String retry(@RequestParam String msg) {
if (4 % 3 == 0) {
return "OK";
}
log.info("服务调用不正常。。。");
throw new RetryException("服务调用不正常。。。");
}
@Recover//作为恢复处理程序的方法调用的注释。
// 重试方法最终会调用标注了@Recover 的方法;需要注意的是发生的异常和入参类型一致时才会回调。
//比如,在上面的方法中有个String类型的参数,那么回调函数中也要有个String类型的参数,参数名相不相同无所谓
public String recover(RetryException e, String message) {
log.info("执行回调方法: {}", message);
System.out.println("我是回调函数");
return "fail";
}
}
4.结果