【发布时间】:2022-06-19 16:23:46
【问题描述】:
我有一个 Spring Boot 应用程序,我们必须在其中对第 3 方 REST 服务进行一些 http 调用。我们可能需要打 1 个电话或数千个电话。
我正在使用 @Async Spring Boot 注释和 CompletableFuture,如下所示:
long start = System.nanoTime();
List<String> list = new ArrayList<>();
List<CompletableFuture<List<String>>> allFutures = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
allFutures.add(httpClient.getStringAsync("Hello"));
}
List<String> unwrappedFutures = allFutures.stream()
.map(CompletableFuture::join)
.flatMap(List::stream)
.collect(Collectors.toList());
list.addAll(unwrappedFutures);
long duration = (System.nanoTime() - start) / 1_000_000;
log.info("Done in {} msecs", duration);
此代码大约需要 2 分钟才能对有 1 秒延迟的 getStringAsync() 方法进行 1000k 次调用。
在“Runtime.getRuntime().availableProcessors()”显示有 12 个内核的笔记本电脑上或在内核数现在似乎只有一个的 EKS 集群上处理所需的时间相同。
我认为我必须配置 ThreadPoolTaskExecutor,以便可用的内核数量越多,处理时间就越短。
但是,我不确定如何确定核心、最大池大小和队列容量。
我想知道池大小是否必须等于列表中的项目数?也就是说,如果列表有 1000 个项目,这意味着我们必须对远程服务进行 1000 次调用,我们需要 1000 个线程吗?这似乎很多。
【问题讨论】:
标签: java spring multithreading spring-boot completable-future