在下面的示例中,我创建了一个 Java 11 httpClient,然后创建了多个并发 HttpRequest。
代码
private static void httpClientExample(){
HttpClient httpClient = HttpClient.newHttpClient();
System.out.println("TP1");
var task1 = httpClient.sendAsync(HttpRequest.newBuilder()
.uri(URI.create("https://www.bing.com/"))
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::uri).thenAccept(System.out::println);
var task2 = httpClient.sendAsync(HttpRequest.newBuilder()
.uri(URI.create("https://openjdk.java.net/"))
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::uri).thenAccept(System.out::println);
var task3 = httpClient.sendAsync(HttpRequest.newBuilder()
.uri(URI.create("https://www.google.co.uk/"))
.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::uri).thenAccept(System.out::println);
System.out.println("Requests Sent");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread Completed");
}
最佳答案
这在 API docs of HttpClient
中没有明确记录。 .但预计 HttpClient 旨在处理多个请求。这在某种意义上暗示于 Introduction to the Java HTTP Client :
Once built, an HttpClient can be used to send multiple requests.
现在,您的问题可能与管理客户端的并发性有关。而不是使用
HttpClient
的相同实例,这与它使用的执行程序服务有很大关系,这是您可以自定义的(请参阅 here ):ExecutorService executorService = Executors.newFixedThreadPool(10);
HttpClient httpClient = HttpClient.newBuilder()
.executor(executorService)
... //more config
.build();
通过这种方式,您可以管理客户端用于运行异步请求的线程池。换句话说:
Is this bad practice?
不
Should each HttpRequest have its own HttpClient?
不
Is there an upper limit on the number of HttpRequests a HttpClient can have?
您必须测试应用程序的最佳并发设置,然后使用相应配置的执行程序服务。
关于Java 11 HttpClient - HttpClient 与并发 HttpRequest 的最佳比率是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64302936/