SpringBoot中使用SpringRetry实现重试机制(重试调用第三方API)

发布时间 2024-01-11 10:11:30作者: 霸道流氓

场景

Springboot+FastJson实现解析第三方http接口json数据为实体类(时间格式化转换、字段包含中文):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/134872936

在调用第三方接口时,可能会出现因为网络波动等原因导致的接口连接超时等短暂的问题。

如何在调用时添加重试机制,可以通过添加注解的方式给指定的方法配置指定的策略执行重试机制。

Spring Retry

Spring Retry提供了自动重新调用失败的操作的功能。这在错误可能是暂时的(例如瞬时网络故障)的情况下很有用。

https://github.com/spring-projects/spring-retry

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi

实现

1、引入项目依赖

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

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

2、启动类添加注解@EnableRetry

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@EnableRetry
public class RuoYiApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(RuoYiApplication.class, args);
    }
}

3、新建接口,用来调用第三方接口

public interface IRetryService {

    String getThirdApiData();

}

4、接口实现

import cn.hutool.http.HttpRequest;
import com.ruoyi.system.service.IRetryService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@Service
public class RetryServiceImpl implements IRetryService {

    //value :针对指定抛出的异常类型,进行重试,这里指定的是Exception
    //maxAttempts :配置最大重试次数,这里配置为10次(包含第一次和最后一次)
    //delay: 第一次重试延迟间隔,这里配置的是2s
    //multiplier :每次重试时间间隔是前一次几倍,这里是1.5倍

    @Override
    @Retryable(value = Exception.class, maxAttempts = 10, backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public String getThirdApiData() {
        System.out.println("调用一次");
        return HttpRequest
                .get("http://127.0.0.1:4523/m1/2858210-0-default/testFastJson")
                .timeout(4000)
                .execute()
                .body();
    }

    @Recover
    public String recover(Exception e){
        return "请求失败";
    }
}

其中在需要重试的方法上添加注解@Retryable,并配置重试策略

value :针对指定抛出的异常类型,进行重试,这里指定的是Exception

maxAttempts :配置最大重试次数,这里配置为10次(包含第一次和最后一次)

delay: 第一次重试延迟间隔,这里配置的是2s

multiplier :每次重试时间间隔是前一次几倍,这里是1.5倍

注解@Recover用来配置所有重试都失败后的回调方法。

5、编写单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RuoYiApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringRetryTest {

    @Autowired
    private IRetryService iRetryService;

    @Test
    public void getThirdApiDataTest() {
        try {
            String thirdApiData = iRetryService.getThirdApiData();
            System.out.println(thirdApiData);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

6、首先将重试次数设置为5次,运行测试结果

当接口一直不通时

 

再将重试次数设置为10次,并在重试过程中将接口打开

 

7、@Retryable注解还可指定重试指定类型的异常

    @Retryable(
        value = { RestClientException.class, TimeoutException.class },
        maxAttempts = 3,
        backoff = @Backoff(delay = 1000, multiplier = 2)
    )

方法会在发生RestClientException或TimeoutException异常时进行重试。

还可排除指定类型的异常

    @Retryable(
        value = { RestClientException.class },
        maxAttempts = 3,
        backoff = @Backoff(delay = 1000, multiplier = 2),
        exclude = { TimeoutException.class }
    )

方法会在发生RestClientException异常时进行重试,但排除了TimeoutException异常。