如何实现 API 调用的重试机制与指数退避策略?

解读

在 Vaadin 全栈 Java 场景下,前端事件最终都会落到服务器端 Java 代码。若服务器需要调用外部 REST/GraphQL/gRPC 接口,网络抖动、对方限流或短暂宕机都会导致瞬时失败。面试官想确认两点:

  1. 你能否把“重试+退避”做成对业务代码无侵入、可配置的通用组件;
  2. 你是否了解国内常见风险:运营商 NAT 超时、阿里云/腾讯云黑洞、微信/支付宝开放平台的 60 s 高频限流、以及金融项目对“幂等性”的强制要求。
    回答时要体现“Java 生态 + Vaadin 线程模型 + 国内运维现实”的综合考量。

知识点

  1. Vaadin 服务器端同步模型:UI 访问必须加 UI.access(),重试代码不能在后台线程直接触碰 UI。
  2. Spring Retry / Resilience4j / Failsafe 三大库在国内项目中最常用,均支持指数退避。
  3. 指数退避公式:initialInterval × multiplierⁿ,上限 maxInterval,配合 jitter 防止“雷群效应”。
  4. 国内云厂商限流返回码:429/503,Header 中常带 X-Ratelimit-Reset,需解析并睡眠到该时刻。
  5. 金融/支付类项目必须携带幂等键(idempotency-key),重试时不允许换号。
  6. Vaadin 异步作业可用 @Async 或 Reactor,但结果写回 UI 必须 UI.access() + push()。
  7. 单元测试:用 MockWebServer + 插件失败几次验证重试次数与退避间隔;集成测试用 Testcontainers 模拟慢接口。

答案

下面给出一份可直接落地的“Vaadin + Spring Boot”方案,兼顾国内常见限流与幂等要求。

  1. 引入依赖
<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
</dependency>
  1. 启动类加 @EnableRetry

  2. 定义重试模板(代码放配置包,可被不同业务注入)

@Configuration
public class RetryConfig {
    @Bean
    public RetryTemplate apiRetryTemplate() {
        RetryTemplate tpl = new RetryTemplate();
        // 指数退避:首次 500 ms,倍数 2,上限 8 s,随机抖动 0.2
        ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy();
        backOff.setInitialInterval(500);
        backOff.setMultiplier(2.0);
        backOff.setMaxInterval(8000);
        backOff.setSleeper(new ThreadWaitSleeper()); // 可单元测试 mock
        tpl.setBackOffPolicy(backOff);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(4); // 共 1+3 次
        tpl.setRetryPolicy(retryPolicy);

        // 国内常见可重试异常
        tpl.registerThrowableClassifier(new BinaryExceptionClassifier(
            throwable -> throwable instanceof ResourceAccessException
                      || throwable instanceof HttpServerErrorException
                      || (throwable instanceof HttpClientErrorException
                          && ((HttpClientErrorException) throwable).getStatusCode() == HttpStatus.TOO_MANY_REQUESTS),
            true));
        return tpl;
    }
}
  1. 封装外部客户端(RestTemplate 或 WebClient),对外暴露幂等键参数
@Component
public class PaymentClient {
    private final RestTemplate rest = new RestTemplate();
    private final RetryTemplate retry;

    public PaymentClient(RetryTemplate apiRetryTemplate) {
        this.retry = apiRetryTemplate;
    }

    public PaymentResp createPayment(PaymentReq req, String idempotencyKey) {
        HttpHeaders h = new HttpHeaders();
        h.setContentType(MediaType.APPLICATION_JSON);
        h.set("Idempotency-Key", idempotencyKey); // 国内支付强制
        HttpEntity<PaymentReq> entity = new HttpEntity<>(req, h);

        return retry.execute(context -> {
            log.warn("第 {} 次调用支付接口", context.getRetryCount() + 1);
            try {
                ResponseEntity<PaymentResp> r = rest.exchange(
                    "https://api.xxx.com/v1/payments", HttpMethod.POST, entity, PaymentResp.class);
                return r.getBody();
            } catch (HttpClientErrorException.TooManyRequests ex) {
                // 读取云厂商返回的 Retry-After
                String reset = ex.getResponseHeaders().getFirst("X-Ratelimit-Reset");
                if (reset != null) {
                    long sleep = Long.parseLong(reset) * 1000 - System.currentTimeMillis();
                    if (sleep > 0) Thread.sleep(sleep);
                }
                throw ex; // 抛出让 RetryTemplate 继续
            }
        });
    }
}
  1. Vaadin 视图层异步调用(不阻塞 UI)
@Route("pay")
public class PayView extends VerticalLayout {
    private final PaymentClient client;
    private final UI ui;

    public PayView(PaymentClient client) {
        this.client = client;
        this.ui = UI.getCurrent();

        Button btn = new Button("发起支付", e -> callPay());
        add(btn);
    }

    private void callPay() {
        // 立即返回,后台线程重试
        CompletableFuture.supplyAsync(() ->
            client.createPayment(new PaymentReq(...), UUID.randomUUID().toString()))
            .whenComplete((resp, ex) -> ui.access(() -> {
                if (ex != null) {
                    Notification.show("支付失败:" + ex.getMessage());
                } else {
                    Notification.show("支付成功,单号:" + resp.getTradeNo());
                }
            }));
    }
}
  1. 配置线程池(防止默认 ForkJoinPool 被 IO 占满)
spring:
  task:
    execution:
      pool:
        core-size: 20
        max-size: 100
        queue-capacity: 500
  1. 单元测试示例
@SpringBootTest
class PaymentClientTest {
    @Autowired PaymentClient client;
    @Autowired RetryTemplate tpl;

    @Test
    void retry3TimesAndSucceed() {
        MockWebServer server = new MockWebServer();
        // 第 1、2 次返回 503,第 3 次 200
        server.enqueue(new MockResponse().setResponseCode(503));
        server.enqueue(new MockResponse().setResponseCode(503));
        server.enqueue(new MockResponse().setBody("{\"tradeNo\":\"T123\"}").setResponseCode(200));
        server.start();

        ReflectionTestUtils.setField(client, "rest",
            new RestTemplateBuilder().rootUri(server.url("/").toString()).build());

        PaymentResp resp = client.createPayment(new PaymentReq(), "key");
        assertEquals("T123", resp.getTradeNo());
        assertEquals(3, server.getRequestCount());
        server.shutdown();
    }
}

通过以上步骤,我们把“重试+指数退避”做成配置化、幂等安全、对 Vaadin UI 无侵入的通用能力,符合国内云环境限流与金融合规要求。

拓展思考

  1. 若接口返回 429 且携带 Retry-After: 120,Spring Retry 默认退避可能小于 120 s,此时应自定义 BackOffPolicy 解析响应头并强制睡眠到指定时刻,否则仍会被拉黑。
  2. 对 GraphQL 场景,错误被包装在 data.errors 数组里,需要自定义 RetryPolicy 解析 JSON 而不是简单看 HTTP 状态码。
  3. 高并发批付场景,可把重试任务拆成消息丢进 RocketMQ/RabbitMQ,利用死信队列做“指数退避 + 人工兜底”,避免单 JVM 重试把线程池打满。
  4. 若项目已用 Resilience4j,可用 Retry + TimeLimiter 组合,再搭配 Vaadin 的 @Push 模式,用 Reactive 流写回 UI,性能比 CompletableFuture 更好。
  5. 国内政企内网常出现“5 分钟断网演练”,重试总时长务必小于事务超时(Spring 默认 30 s),否则数据库行锁未释放会导致雪崩;可把 maxAttempts 与 maxInterval 乘积控制在 25 s 以内,并配合断路器快速失败。