一、背景

在项目中,我们有时候需要调用第三方接口进行业务请求,比如调用第三方短信平台发送短信,但有时候会出现第三方服务不稳定或者网络抖动而导致的请求失败,这时我们通常会用try-catch、while等方式进行重试,但是这样写的代码不优雅,如果还要加上重试的次数和每次重试的间隔,就更加繁琐了,那么有没有更优雅的写法呢?可以使用spring-retry。

二、 使用方式

1、 引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <version>1.3.0</version>
        </dependency>

2、在启动类增加@EnableRetry注解

@EnableRetry
@SpringBootApplication
public class RetryApplication {

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

3、在需要重试的方法上添加@Retryable

    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public String remoteHttpRequest() {
        int random = new Random().nextInt(4);
        System.out.println("remote http request, random=" + random);
        if (random < 2) {
            System.out.println("remote http request请求异常!");
            throw new RuntimeException("random < 2");
        }
        System.out.println("成功调用!");
        return "SUCCESS";
    }

value:抛出指定异常才会重试
include:和value一样,默认为空,当exclude也为空时,默认所有异常
exclude:指定不处理的异常
maxAttempts:最大重试次数,默认3次
backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。

4、测试效果
image-1686793357167
image-1686793363349

打赏
支付宝 微信
上一篇 下一篇