为什么这个线程池不同时执行 HTTP 请求呢?

Why doesn't this thread pool execute HTTP requests simultaneously?

我写了几行代码,将向我机器上的服务 运行ning 发送 50 个 HTTP GET 请求。该服务将始终 sleep 1 秒和 return 带有空主体的 HTTP 状态代码 200。正如预期的那样,代码 运行s 持续了大约 50 秒。

为了稍微加快速度,我尝试创建一个具有 4 个线程的 ExecutorService,这样我就可以同时向我的服务发送 4 个请求。我预计代码 运行 大约 13 秒。

final List<String> urls = new ArrayList<>();
for (int i = 0; i < 50; i++)
    urls.add("http://localhost:5000/test/" + i);

final RestTemplate restTemplate = new RestTemplate();

final List<Callable<String>> tasks = urls
        .stream()
        .map(u -> (Callable<String>) () -> {
            System.out.println(LocalDateTime.now() + " - " + Thread.currentThread().getName() + ": " + u);
            return restTemplate.getForObject(u, String.class);
        }).collect(Collectors.toList());

final ExecutorService executorService = Executors.newFixedThreadPool(4);

final long start = System.currentTimeMillis();
try {
    final List<Future<String>> futures = executorService.invokeAll(tasks);

    final List<String> results = futures.stream().map(f -> {
        try {
            return f.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new IllegalStateException(e);
        }
    }).collect(Collectors.toList());
    System.out.println(results);
} finally {
    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);
}

final long elapsed = System.currentTimeMillis() - start;
System.out.println("Took " + elapsed + " ms...");

但是 - 如果您查看调试输出的秒数 - 似乎前 4 个请求是同时执行的,但所有其他请求都是一个接一个地执行的:

2018-10-21T17:42:16.160 - pool-1-thread-3: http://localhost:5000/test/2
2018-10-21T17:42:16.160 - pool-1-thread-1: http://localhost:5000/test/0
2018-10-21T17:42:16.160 - pool-1-thread-2: http://localhost:5000/test/1
2018-10-21T17:42:16.159 - pool-1-thread-4: http://localhost:5000/test/3
2018-10-21T17:42:17.233 - pool-1-thread-3: http://localhost:5000/test/4
2018-10-21T17:42:18.232 - pool-1-thread-2: http://localhost:5000/test/5
2018-10-21T17:42:19.237 - pool-1-thread-4: http://localhost:5000/test/6
2018-10-21T17:42:20.241 - pool-1-thread-1: http://localhost:5000/test/7
...
Took 50310 ms...

因此出于调试目的,我将 HTTP 请求更改为 sleep 调用:

// return restTemplate.getForObject(u, String.class);
TimeUnit.SECONDS.sleep(1);
return "";

现在代码按预期运行:

...
Took 13068 ms...

所以我的问题是为什么带有 sleep 调用的代码按预期工作而带有 HTTP 请求的代码却没有?我怎样才能让它按照我预期的方式运行?

根据信息,我认为这是最可能的根本原因:

The requests you make are done in parallel but the HTTP server which fulfils these request handles 1 request at a time.

因此,当您开始发出请求时,executor service fires up the requests concurrently,因此您同时获得了前 4 个。

但是 HTTP 服务器 可以响应 请求一次一个 即在 1每个第二。

现在,当第一个请求完成时,执行程序服务选择另一个请求并触发它,这一直持续到最后一个请求。

4 个请求在 HTTP 服务器上一次被阻止,一个接一个地串行服务。

要获得此理论的 Proof of Concept,您可以使用消息服务(队列),它可以同时从 4 个通道接收测试。那应该会减少时间。