SpringBoot中使用@Retryable注解进行重试
SpringBoot中使用@Retryable注解进行重试
有功能需要重试时,可以使用Spring的 @Retryable 注解.
参数含义:
value:抛出指定异常才会重试
exclude:指定不处理的异常
maxAttempts:最大重试次数,默认3次
backoff:重试等待策略,默认使用@Backoff,
@Backoff的value(相当于delay)表示隔多少毫秒后重试,默认为1000L;
multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试。
依赖包:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
添加 @EnableRetry 注解
@SpringBootApplication(scanBasePackages = {"com.example.demo"})
@EnableRetry
public class DemoApplication {
}
使用示例:
controller
@Autowired
private RetryService retryService;
@RequestMapping("testsz")
public RestResultDTO getStudentInfo() throws Exception {
retryService.doSomething();
return RestResultDTO.ok();
}
service
public interface RetryService {
public void doSomething();
}
impl
import com.axa.dataservice.backend.service.RetryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class RetryServiceImpl implements RetryService{
@Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 3000,multiplier = 1.5))
public void doSomething() {
log.info("doSomething start.");
int result = 1/0;
log.info("doSomething end.");
}
/**
* @Recover 的返回类型,必须跟 @Retryable修饰的方法返回值一致。否则不生效。
*
*/
@Recover
public void recover(Exception e) {
log.info("retry failed recover");
log.info("retry Exception:"+e);
//是否需要入库记录
}
}
执行结果:
可以看到,@Retryable 修饰的方法执行了3次。仍旧失败后,会执行 @Recover 修饰的方法。
也可以使用下面发生执行异常重试
@Slf4j
@Component
@EnableRetry
public class RecoryTest {
@Retryable(value = {RetryException.class}, // 指定发生的异常进行重试
maxAttempts=5, // 重试次数, 默认即为3
backoff = @Backoff(delay = 2000L, multiplier = 2)) // 每次重试延迟毫秒数 及 延迟倍数
@Async
public void retry() {
log.info("retry start");
throw new RetryException("retry fail");
}
@Recover
public void recover (RetryException e) {
log.error("recovery,{}",e.getMessage());
}
}