springboot使用retry重试机制

当我们调用一个外部接口可能由于网络等原因造成请求失败,再去尝试几次就成功了,这就是重试机制。

首先引入依赖包:

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
        
<!-- spring重试机制 -->
<dependency>
     <groupId>org.springframework.retry</groupId>
      <artifactId>spring-retry</artifactId>
</dependency>

service实现类

@EnableRetry // 开启重试机制
@Service
public class RetryDemoService {

    // TODO 不会被重试,aspect失效,与spring aop事务处理方式类似
    public void print() throws Exception {
        call();
    }

    // 要执行的业务方法,发生指定异常后重试
    @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(5000))
    public void call() throws Exception {
        System.out.println("start retry...");
        throw new RemoteAccessException("RPC调用异常");
    }

    // 重试失败后的回调方法
    @Recover
    public void recover(RemoteAccessException e) {
        // 记录log
        System.out.println(e.getMessage());
    }

    @Recover
    public void recover(NullPointerException e) {
        // 记录log
        System.out.println(e.getMessage());
    }

}

 测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class RetryTest {

    @Autowired
    RetryDemoService retryDemoService;

    @Test
    public void test() throws Exception {
        retryDemoService.call();
        // retryDemoService.print();
    }

}

测试结果

@Retryable注解 

注解参数:

        value:指定发生的异常进行重试

        include:和value一样,默认空,当exclude也为空时,所有异常都重试

        exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试

        maxAttemps:重试次数,默认3

        backoff:重试补偿机制,默认没有

@Backoff注解 

        delay:指定延迟后重试 

        multiplier:指定延迟的倍数,比如delay=5000l,multiplier=3时,第一次重试为5秒后,第二次为15秒,第三次为45秒

@Recover 

        当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调

特别要注意第一点,@Recover ,@Retryable修饰的方法可以有返回值,但是二者返回值类型必须一致

发布了10 篇原创文章 · 获赞 0 · 访问量 388

猜你喜欢

转载自blog.csdn.net/ayudnl/article/details/103217603