SpringBoot如何优雅的实现重试功能

使用背景

在有些特定场景,如和第三方对接。
我们调用接口时需要支持重试功能,第一次调用没成功,我们需要等待x秒后再次调用。
通常会设置重试次数,避免业务。
一般我们会这样写

public ApiResponse<Boolean> test() {
	//模拟调用
	System.out.println("开始调用,第" + num + "次");
	//业务逻辑
	boolean result = false;
	if (result) {
		System.out.println("执行完成!");
	} else if (num >= totalNum) {
		System.out.println("重试结束");
		num = 1;
	} else {
		System.out.println("重试");
		++num;
		test();
	}
	return ApiResponse.ok(true);
}

这样写本身,没什么问题。
但是如果多个接口都需要重试的话,代码就不优雅了。

spring-retry介绍

spring系列的spring-retry是另一个实用程序模块,
可以帮助我们以标准方式处理任何特定操作的重试。
在spring-retry中,所有配置都是基于简单注释的。

快速使用

加入依赖

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

开启Retry

启动上增加注解@EnableRetry

@EnableRetry

使用

@GetMapping("test")
@Retryable(value = Exception.class,maxAttempts = 5,backoff = @Backoff(delay = 2000,multiplier = 1.5))
public ApiResponse<Boolean> test() {
	System.out.println("开始调用,第" + num + "次");
	boolean result = false;
	if (!result){
		num++;
		throw new BizException("调用失败,需要重试");
	}
	System.out.println("执行完成");
	return ApiResponse.ok(true);
}

参数

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

努力的蚂蚁【你若】

如果帮助到了您,一分也是爱

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

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

打赏作者

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

抵扣说明:

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

余额充值