天天看点

Spring - retry重试机制

关于spring-retry

有些时候我们对于的一些行为遭遇到意外时需要重试时,如远程调用其他接口失败,数据相关的事务失败,这时我们就需要重试机制了。spring-retry通过注解声明式的解决重试机制,功能齐全,简单好用。

主要注解

@EnableRetry :加在主类上,声明启用重试机制

@SpringBootApplication
@RestController
@EnableCaching
@EnableFeignClients
@EnableRetry
public class Application {

    @GetMapping("/")
    String home() {
        return "Spring is here!";
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
           

@Retryable:加在需要重试的方法上,可通过参数配置相关的行为

  • value :指明抛出什么异常时进行重试
  • include :指定处理的异常类和value一样,默认为空,当exclude也为空时,默认所有异常
  • exclude :指定不处理的异常
  • maxAttempts :重试次数,默认为3
  • backoff :补偿策略,默认为@Backoff 注解,其可配置重试等待间隔时间等

@Backoff : 注解,其可配置重试等待间隔时间等

@Recover:用于@Retryable重试失败后处理方法,此注解注释的方法参数一定要是@Retryable抛出的异常,否则无法识别;它可识别@Retryable的失败的异常进行相关的处理

@Service
public class TestService {
    @Retryable(value = Exception.class,maxAttempts = 4, backoff = @Backoff)
    public void service(){
        doSometing....
        throw new RuntimeException("服务调用异常");
    }
    
    //重试失败的处理
    @Recover
    private void callback(Exception e){
        log.error(e.getMessage());
    }

}
           

注意

Retry的实现是通过代理实现的,代理我们知道代理对象注入相关增强后是回调目标对象方法,所以Retry服务在本类方法中调用是不起作用的。