天天看点

Spring-retry 优雅地重试机制Spring-retry 优雅地重试机制

Spring-retry 优雅地重试机制

如何有什么问题出错需要重试,不用繁琐的写for循环去手动重试,可以使用Spring-retry优雅地实现.

第一步:导入spring-retry
build.gradle 中添加代码:
dependencies {
    compile('org.springframework.retry:spring-retry:1.2.2.RELEASE')
}
           
第二步:在类上添加注解 @EnableRetry
@EnableRetry
public class  needRetryService {
       public void needRetryFunction {
           if (condition){
           new SomeException("some exception occur!");
       }
}
           
第三步:在需要重试的方法上添加注解 @Retryable
@EnableRetry
public class  needRetryService {

      @Retryable(include = SomeException.class, maxAttempts = 3)
       public void needRetryFunction {
           if (condition){
          throws new SomeException("some exception occur!");
       }
}
           

到这里就完成重试功能了,解释一下工作过程:

当调用needRetryService中的needRetryFunction时,如果抛出了异常SomeException,就会被重试,默认重试3次。

但是如果三次都失败了,想要捕获异常,给用户良好的用户体验,就需要第四步。

第四步:添加重试失败之后处理的方法
@Recover
    public void exceptionHandler(SomeException e) {
        log.error("some exception " + e.getMessage());
    }
           

重试第三次仍然抛出异常,就会执行exceptionHandler方法,并输出异常信息。

继续阅读