在api服务接口中,如果接口的逻辑复杂,内部处理时间过长,导致请求超时,接口中的逻辑处理终端怎么办?
例如:一个post接口/aaa,其中循环调用了10000次接口/bbb,如果等10000次/bbb接口都返回后再结束/aaa接口的请求,这样会导致/aaa接口超时。
如果遇到这种情况,我们可以在接口/aaa中的启动一个线程,让线程来异步的调用/bbb接口,这样/aaa接口就可以立马返回,让/bbb接口在线程中执行。
代码:
@RequestMapping(value = "/batchCreateTeam", method = RequestMethod.POST)
@ResponseBody
public void userIdNumCreateTeam(@RequestBody CreateTeamRequestBody requestBody)
throws IOException, InterruptedException, ExecutionException {
HttpClient client = HttpClient.newHttpClient();
// 创建第一个HTTP请求
HttpRequest request1 = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/team/create"))
.POST(HttpRequest.BodyPublishers.ofString("{}")) // 假设请求体为空字符串
.build();
// 启动一个线程来异步调用另一个HTTP接口10000次
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
int count = 0;
while (count < 10000) {
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request1, HttpResponse.BodyHandlers.ofString());
try {
HttpResponse<String> response = futureResponse.get();
// 处理响应内容(这里只是打印出来)
System.out.println("Response from before: " + response.body());
count++;
if (count % 100 == 0) {
System.out.println("Progress: " + count); // 每100次打印一条日志
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
});
// 等待异步操作完成,并关闭线程池
// 如果不想等线程结束在返回,就不写下面两句
future.get();
executor.shutdown();
}