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

场景

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

Springboot+FastJson实现解析第三方http接口json数据为实体类(时间格式化转换、字段包含中文)_fastjson 发送http请求 接收实体,出现日期转换异常-CSDN博客

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

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

Spring Retry

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

GitHub - spring-projects/spring-retry

注:

博客:
霸道流氓气质-CSDN博客

实现

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异常。

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值