Spring boot Retry的使用
在很多场景中需要重试,比如说在处理外部请求时,有可能会遇到对方的网络连接断开,或者其他不可控的原因,无法请求到数据,需要重新发送请求的情况下,因此使用Spring boot Retry 可以定义重试的方法和重试的次数。
一、包准备
Springboot Retry是依赖于springboot 框架,在maven或者gradle 中加入springboot retry 包
gradle:
compile('org.springframework.retry:spring-retry')
compile('org.springframework.boot:spring-boot-starter')
(如果报错Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.annotation.Around,可以加上
compile('org.aspectj:aspectjweaver')
二、Demo
1.在启动类application中加上注解,@EnableRetry 允许重试
2.springboot Retry 是基于->异常<-来发起重试的,在实现中主要把握的就是抛出异常和接收异常
代码:
首先定义个异常:
public class RetryException extends RuntimeException {
private String code;
private String msg;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
重试方法:
@Service
public class RetryDemoService {
private Logger log = LoggerFactory.getLogger(RetryDemoService.class);
int i = 1;
@Retryable(value = {RuntimeException.class},maxAttempts = 4,backoff = @Backoff(delay = 5000,multiplier = 1))
public String retry(){
log.info("重试测试...");
i++;
if(i == 3){
return i+"";
}
RetryException retryException=new RetryException();
retryException.setCode("9999");
retryException.setMsg("连接超时");
throw retryException;
}
@Recover
public String recover(RetryException e){
log.info("recover::");
log.info(e.getMessage());
return "6";
}
}
在重试方法头上加上如下注解
@Retryable(value = {RuntimeException.class},maxAttempts = 4,backoff = @Backoff(delay = 5000,multiplier = 1))
value:表明捕捉的异常,也就是说捕捉到哪个异常后,触发重试
maxAttempts:重试次数,默认是3,本次方法中是5s
backoff:指的是重试延迟ms. multiplier 指的是延迟倍数1为1倍,也就是5000*1
在本次实现中,特意抛出自定义的异常,好让注解能够及时捕获重试,看到效果
用@Recover 修饰的表示该方法为修复方法,也就是在所有重试次数都用完依旧抛出异常时,会调用该方法,可以作为记录错误处理。