<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.retry.annotation.EnableRetry;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableRetry
public class RetryApplication {
public static void main(String[] args) {
SpringApplication.run(RetryApplication.class, args);
}
}
package org.example.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.example.service.RetryService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
@Slf4j
public class RetryServiceImpl implements RetryService {
/**
* interceptor:可以通过该参数,指定方法拦截器的bean名称
* value:抛出指定异常才会重试
* include:和value一样,默认为空,当exclude也为空时,默认所以异常
* exclude:指定不处理的异常
* maxAttempts:最大重试次数,默认3次
* backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。
* @return "${sobot.url}"
*/
@Override
@Retryable(value = Exception.class, maxAttemptsExpression ="${retry.maxAttempts}" , backoff = @Backoff(delayExpression = "${retry.delay}", multiplierExpression = "${retry.multiplier}"))
public String retry() {
log.info("retry............"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
int i=10/0;
return "hello";
}
@Recover
public String doRecover(Throwable throwable){
log.info("the message:{}",throwable.getMessage());
return "出现异常了";
}
//若retry里面有调用请求,recover里面不要嵌套调用retry,会出现http请求连接数达到上限,出现无法调用的情况
@Recover
public String doRecover(Throwable throwable,boolean ifFlag){
log.info("the message:{},flag:{}",throwable.getMessage(),ifFlag);
return "出现异常了";
}
}