Java 后端 / 系统课时
实现超时、重试与退避
实现超时、重试与退避
本课使用 Resilience4j 为 Spring Boot 3 的外部 HTTP 调用增加超时、有限重试、指数退避和可控重试条件。最终效果是:慢调用会被及时终止,瞬时故障只重试有限次数,永久性错误不会被无意义放大。
学习目标
- 配置调用超时、最大重试次数与指数退避
- 只对幂等且可能恢复的异常执行重试
- 通过日志和接口结果验证成功、超时与重试耗尽路径
明确策略边界
超时负责限制单次调用占用资源的时间,重试负责处理短暂故障,两者不能互相替代。没有超时的重试可能让每次尝试都无限等待;没有次数上限的重试会放大流量并拖垮下游。
只有幂等操作才适合自动重试。查询通常可以重试;创建订单、扣款等写操作必须依赖幂等键或服务端去重机制。400、401、403 等请求本身错误通常不会因等待而恢复,不应重试;连接失败、超时和部分 5xx 才可能属于瞬时故障。

添加依赖
以下是 pom.xml 片段示例,依赖父 POM 已定义 resilience4j.version。它引入 Resilience4j 的 Spring Boot 3 集成和 AOP 支持。
<dependencies>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>${resilience4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>生效行为:Spring 会识别 @Retry 与 @TimeLimiter 等注解,并从配置文件读取对应实例参数。父 POM 应把 resilience4j.version 锁定为项目验证过的 Spring Boot 3 兼容版本。
配置超时、次数与退避
下面配置把单次调用限制为 800 毫秒,最多尝试 3 次。首次失败后等待 200 毫秒,之后按 2 倍增长。max-attempts 包含第一次调用,因此最多只会额外重试 2 次。
resilience4j:
timelimiter:
instances:
inventoryClient:
timeout-duration: 800ms
cancel-running-future: true
retry:
instances:
inventoryClient:
max-attempts: 3
wait-duration: 200ms
enable-exponential-backoff: true
exponential-backoff-multiplier: 2
retry-exceptions:
- java.net.ConnectException
- java.net.SocketTimeoutException
- java.util.concurrent.TimeoutException
- com.example.inventory.RetryableInventoryException
ignore-exceptions:
- com.example.inventory.NonRetryableInventoryException验证方法:启动应用时不应出现配置绑定错误;触发失败调用后,日志中的尝试间隔应接近 200 毫秒和 400 毫秒。调度、线程切换和日志时间精度会带来少量偏差。
编写可控重试的客户端
下面示例使用 CompletableFuture 适配 TimeLimiter,并把 4xx 与 5xx 转换为不同异常。两个注解分别绑定同名策略;回退方法在尝试耗尽或遇到不可重试异常后统一转换为 InventoryUnavailableException,再由全局异常处理映射为 503。
package com.example.inventory;
import io.github.resilience4j.retry.annotation.Retry;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import java.util.concurrent.CompletableFuture;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
@Service
public class InventoryClient {
private final RestClient restClient;
public InventoryClient(RestClient.Builder builder) {
this.restClient = builder
.baseUrl("http://inventory-service:<PORT>")
.build();
}
@Retry(name = "inventoryClient", fallbackMethod = "fallback")
@TimeLimiter(name = "inventoryClient")
public CompletableFuture<Integer> getAvailableStock(long productId) {
return CompletableFuture.supplyAsync(() -> {
var response = restClient.get()
.uri("/api/inventory/{id}", productId)
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, (request, result) -> {
throw new RetryableInventoryException(
"Inventory service failed: " + result.getStatusCode());
})
.onStatus(HttpStatusCode::is4xxClientError, (request, result) -> {
throw new NonRetryableInventoryException(
"Inventory request is not retryable: " + result.getStatusCode());
})
.body(InventoryResponse.class);
if (response == null) {
throw new NonRetryableInventoryException("Empty inventory response");
}
return response.available();
});
}
private CompletableFuture<Integer> fallback(long productId, Throwable error) {
return CompletableFuture.failedFuture(
new InventoryUnavailableException(productId, error));
}
public record InventoryResponse(int available) {
}
}配套异常类:
package com.example.inventory;
public class RetryableInventoryException extends RuntimeException {
public RetryableInventoryException(String message) {
super(message);
}
}package com.example.inventory;
public class NonRetryableInventoryException extends RuntimeException {
public NonRetryableInventoryException(String message) {
super(message);
}
}package com.example.inventory;
public class InventoryUnavailableException extends RuntimeException {
public InventoryUnavailableException(long productId, Throwable cause) {
super("Inventory unavailable for product " + productId, cause);
}
}预期结果:
正常响应:第一次调用成功,返回库存数量,不发生重试
瞬时故障:最多执行 3 次,重试前约等待 200ms、400ms
单次超时:每次尝试超过 800ms 后失败并进入下一次重试
不可重试错误:遇到 4xx 或 NonRetryableInventoryException 后直接停止
尝试耗尽:执行 fallback,最终抛出 InventoryUnavailableException端口、时间与线程调度结果会因环境不同而变化。生产项目还应为异步执行配置受控线程池,避免 CompletableFuture 默认公共线程池成为新的共享瓶颈。
校验总耗时与流量放大
三次尝试并不代表总耗时只有 800 毫秒。最坏情况下,总耗时约为三次超时之和,再加两次退避等待,即 毫秒。上游接口的超时预算必须大于该值,否则上游可能先断开,而后台仍在继续尝试。
重试还会放大下游流量。若原始请求速率为每秒 100 次,全部请求都重试两次,短时间内下游可能承受接近每秒 300 次尝试。因此应限制重试次数,加入抖动,并配合熔断、并发隔离和全链路超时预算。
常见失败处理
若注解没有生效,先确认类由 Spring 管理、调用经过代理,并已引入 AOP 依赖;同类内部直接调用注解方法会绕过代理。若所有异常都被重试,检查是否把过宽的 Exception 配进了 retry-exceptions。
若超时后后台任务仍持续运行,说明底层客户端未响应中断或取消。应优先使用支持连接超时、读取超时和取消的 HTTP 客户端,并把底层超时设置得不大于 TimeLimiter 的预算。