Java中重试功能实现

背景

在项目中,偶尔出现一些超时或者请求异常的情况,需要进行重试,这个时候,你会怎么处理?

Spring Retry

Spring Retry是Spring框架的一个扩展模块,专门用于提供声明式重试的功能。

1、添加依赖

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

2、启动类增加@EnableRetry注解

3、使用

1)方式1:在对应方法上加上@Retryable注解

@GetMapping("/spring-retry")
@Retryable(maxAttempts = 5, backoff = @Backoff(delay = 1000, multiplier = 2))// 重试5次,初始间隔1秒,间隔乘数2
public String springRetry() {
	System.out.println(new Date() + "请求中...");
	int i = 1 / 0;
	return "请求成功";
}

2)方式2:注入RetryTemplate使用
添加配置

@Configuration
@EnableRetry
public class RetryConfig {

	@Bean
	public RetryTemplate retryTemplate() {
		RetryTemplate retryTemplate = new RetryTemplate();
		ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
		backOffPolicy.setInitialInterval(1000); // 初始间隔 1 秒
		backOffPolicy.setMultiplier(2.0); // 间隔乘数
		backOffPolicy.setMaxInterval(10000); // 最大间隔 10 秒
		retryTemplate.setBackOffPolicy(backOffPolicy);
		SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
		simpleRetryPolicy.setMaxAttempts(3);
		retryTemplate.setRetryPolicy(simpleRetryPolicy); // 最大重试次数
		return retryTemplate;
	}
}

依赖注入使用

@Autowired
private RetryTemplate retryTemplate;

@GetMapping("/spring-retry2")
public String springRetry2() {
	return retryTemplate.execute(context -> {
		System.out.println(new Date() + "请求中...");
		int i = 1 / 0;
		return "请求成功";
	});
}

自定义实现

自定义实现重试逻辑,思路大概就是使用循环、条件判断、线程休眠等。

1、工具类

public class RetryUtils {

	private static final int MAX_RETRIES = 3; // 最大重试次数
	private static final long BASE_BACKOFF_MILLIS = 1000; // 基础退避时间(毫秒)
	private static final double BACKOFF_MULTIPLIER = 2.0; // 退避时间倍数

	/**
	 * 执行带重试逻辑的任务
	 *
	 * @param task 需要重试的任务
	 * @param <T>  任务返回类型
	 * @return 任务执行结果
	 * @throws Exception 如果所有重试都失败,则抛出异常
	 */
	public static <T> T executeWithRetry(Callable<T> task) throws Exception {
		int attempt = 0;
		long backoffMillis = BASE_BACKOFF_MILLIS;
		while (true) {
			attempt++;
			try {
				return task.call(); // 尝试执行任务
			} catch (Exception e) {
				if (attempt > MAX_RETRIES) {
					throw new RuntimeException("超过最大重试次数");
				}
				// 应用退避策略,等待一段时间后重试
				TimeUnit.MILLISECONDS.sleep(backoffMillis);
				backoffMillis = (long) (backoffMillis * BACKOFF_MULTIPLIER);
			}
		}
	}
}

2、使用

@GetMapping("/customize")
public String customize() throws Exception {
	return RetryUtils.executeWithRetry(() -> {
		System.out.println(new Date() + "请求中...");
		int i = 1 / 0;
		return "请求成功";
	});
}

总结

总的来说,上面主要介绍了Spring Retry和自定义实现,都是同步的,除此之外,Guava、Resilience4j等框架也是支持的。

Google的Guava库也提供了简单的重试机制,可以使用其Retryer类来创建重试策略。Guava的重试机制较为轻量级,易于集成到现有的项目中。

Resilience4j是一个轻量级的容错库,它提供了重试、熔断、限流等功能。Resilience4j的Retry模块允许你配置重试策略,并可以与其他容错机制结合使用。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员Forlan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值