在 Java 中,API 接口重试(通常是 HTTP 接口调用重试)有几种常见方案,从原生实现到主流框架,下面按使用场景给你总结一下。
适合简单场景:
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);
✅ 优点:零依赖
❌ 缺点:功能弱(无指数退避、无条件控制)
@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";
}
}
✅ 支持:
RestTemplate 本身不支持重试,一般配合 Spring Retry 或拦截器。
OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
⚠️ 只重试连接失败,不重试业务异常(如 500)
HttpRequestRetryHandler retryHandler = (exception, executionCount, context) ->
executionCount <= 3;
CloseableHttpClient client = HttpClients.custom()
.setRetryHandler(retryHandler)
.build();
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);
}
}
✅ 微服务场景首选
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;
});
}
✅ 适合重试
❌ 不适合重试
✅ 推荐策略:
| 方式 | 适用场景 | 推荐度 |
|---|---|---|
| for 循环 | 简单脚本 | ⭐⭐ |
| Spring Retry | Spring 项目 | ⭐⭐⭐⭐⭐ |
| OkHttp | HTTP 层 | ⭐⭐⭐⭐ |
| Feign | 微服务 | ⭐⭐⭐⭐⭐ |
如果你能告诉我:
我可以给你可直接用的完整代码示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。