温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java API接口如何重试

发布时间:2026-10-02 12:55:10 来源:亿速云 阅读:90 作者:小樊 栏目:编程语言

在 Java 中,API 接口重试(通常是 HTTP 接口调用重试)有几种常见方案,从原生实现到主流框架,下面按使用场景给你总结一下。


一、原生方式(不依赖框架)

1️⃣ 简单 for 循环重试

适合简单场景:

public <T> T callWithRetry(Callable<T> task, int maxRetry) throws Exception {
    Exception lastException = null;
    for (int i = 0; i < maxRetry; i++) {
        try {
            return task.call();
        } catch (Exception e) {
            lastException = e;
            Thread.sleep(1000); // 重试间隔
        }
    }
    throw lastException;
}

调用:

String result = callWithRetry(() -> httpClient.get("/api"), 3);

✅ 优点:零依赖
❌ 缺点:功能弱(无指数退避、无条件控制)


二、Spring Retry(推荐 ✅)

2️⃣ 使用 @Retryable

依赖

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
</dependency>

启用重试

@EnableRetry
@SpringBootApplication
public class Application {}

接口调用方法

@Service
public class ApiService {

    @Retryable(
        value = {RuntimeException.class},
        maxAttempts = 3,
        backoff = @Backoff(delay = 1000, multiplier = 2)
    )
    public String callApi() {
        // 调用第三方接口
        return restTemplate.getForObject(url, String.class);
    }

    @Recover
    public String recover(Exception e) {
        return "fallback";
    }
}

✅ 支持:

  • 异常类型控制
  • 重试次数
  • 退避策略(指数退避)

三、HTTP 客户端自带重试

3️⃣ RestTemplate(不推荐手写)

RestTemplate 本身不支持重试,一般配合 Spring Retry 或拦截器。


4️⃣ OkHttp 重试(推荐 HTTP 层)

OkHttpClient client = new OkHttpClient.Builder()
    .retryOnConnectionFailure(true)
    .build();

⚠️ 只重试连接失败,不重试业务异常(如 500)


5️⃣ Apache HttpClient 重试

HttpRequestRetryHandler retryHandler = (exception, executionCount, context) ->
    executionCount <= 3;

CloseableHttpClient client = HttpClients.custom()
    .setRetryHandler(retryHandler)
    .build();

四、声明式 HTTP 客户端(Feign)

6️⃣ OpenFeign + Spring Retry

feign:
  client:
    config:
      default:
        retryer: com.example.MyRetryer
public class MyRetryer implements Retryer {
    public void continueOrPropagate(RetryableException e) {
        if (attempts++ >= 3) throw e;
        sleep(1000);
    }
}

✅ 微服务场景首选


五、异步 / 响应式重试

7️⃣ CompletableFuture

public <T> CompletableFuture<T> retryAsync(Supplier<T> supplier, int times) {
    return CompletableFuture.supplyAsync(() -> {
        for (int i = 0; i < times; i++) {
            try {
                return supplier.get();
            } catch (Exception e) {
                if (i == times - 1) throw e;
            }
        }
        return null;
    });
}

六、重试设计建议(很重要 ⚠️)

✅ 适合重试

  • 网络超时
  • 5xx 错误
  • 幂等接口

❌ 不适合重试

  • 4xx(参数错误)
  • 非幂等写操作(下单、支付)

✅ 推荐策略:

  • 指数退避(1s → 2s → 4s)
  • 最大重试 3 次
  • 加熔断(Sentinel / Hystrix)

七、总结对比

方式 适用场景 推荐度
for 循环 简单脚本 ⭐⭐
Spring Retry Spring 项目 ⭐⭐⭐⭐⭐
OkHttp HTTP 层 ⭐⭐⭐⭐
Feign 微服务 ⭐⭐⭐⭐⭐

如果你能告诉我:

  • 用的什么框架(Spring / Spring Boot / 微服务)
  • 同步还是异步
  • HTTP 客户端类型

我可以给你可直接用的完整代码示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手