You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何封装REST API调用统一处理认证与限流重试逻辑?

实现通用REST API调用处理函数

要封装统一的重试逻辑,你可以利用Java的泛型和函数式接口来创建一个通用方法。以下是具体实现步骤:

1. 定义自定义函数式接口

由于标准Supplier不支持抛出检查型异常,我们需要创建一个允许抛出IntegrationException和InterruptedException的接口:

@FunctionalInterface
interface ApiCall<T> {
    T execute() throws IntegrationException, InterruptedException;
}

2. 实现通用处理方法

编写泛型方法handleIntegration,封装限流、调用、异常处理和重试逻辑:

private <T> T handleIntegration(ApiCall<T> apiCall) throws IntegrationException, InterruptedException {
    // 执行限流消耗
    bucket.consume();
    
    T response = null;
    try {
        // 首次执行API调用
        response = apiCall.execute();
    } catch (IntegrationException e) {
        if (e.getStatusCode() == 401) {
            // 刷新令牌后重试
            this.newAccessFromRefreshToken();
            response = apiCall.execute();
        } else if (e.getStatusCode() == 429) {
            // 休眠后重试
            Thread.sleep(500);
            response = apiCall.execute();
        } else {
            // 其他异常直接抛出
            throw e;
        }
    }
    return response;
}

3. 调用示例

现在你可以用简洁的方式调用各种API接口,无需重复编写异常处理逻辑:

// 调用客户接口
CustomersResponse customersResponse = handleIntegration(() -> connection.customers.findCustomersResponse());

// 调用员工接口
EmployeeResponse employeeResponse = handleIntegration(() -> connection.employees.findEmployeesResponse());

可选优化建议

  • 重试次数控制:当前仅重试一次,可添加参数指定最大重试次数,避免无限重试。
  • 线程安全:newAccessFromRefreshToken方法若涉及共享资源,建议添加同步机制防止多线程重复刷新令牌。
  • 可配置休眠时间:将429异常的休眠时间改为可配置参数,提升灵活性。
  • 异常包装:若不想向上抛出InterruptedException,可将其包装为运行时异常处理。

内容的提问来源于stack exchange,提问作者jalmen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:40:38