Springboot @Retryable重试机制实现

场景

在开发的过程中,有的时候我们需要调用第三方的服务或方法 这时候可能会出现网络异常 等一些意外的情况这时候重试机制就会有用了

实现的步骤

  1. 加入引用
<dependency>
	<groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
  1. .在启动的主程序上加注解
@EnableRetry 
  1. 在需要重试的方法上加入重试的注解
    @Override
    @Retryable(value = {Exception.class}, maxAttempts = 20, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public void testRetry() throws Exception {
        System.out.println("测试重试方法: 执行时="+System.currentTimeMillis());
        throw new Exception();
    }
参数详情
value

表示遇到该异常进行重试操作(也可以是自定义的异常)

maxAttempts

重试最大的次数

重试等待策略

@Backoffvalue默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。
4.重试到达最大的次数(maxAttempts)之后的回调方法 @Recover

   @Recover
    private void testRetryRecover(){
        System.out.println("方法重试失败次数到上限了");
    }

猜你喜欢

转载自blog.csdn.net/wolf2s/article/details/107357026