gpt4 book ai didi

Java 11 HttpClient - HttpClient 与并发 HttpRequest 的最佳比率是多少

转载 作者:行者123 更新时间:2023-12-04 00:15:34 32 4
gpt4 key购买 nike

在下面的示例中,我创建了一个 Java 11 httpClient,然后创建了多个并发 HttpRequest。

  • 这是不好的做法吗?
  • 每个 HttpRequest 都应该有自己的 HttpClient 吗?
  • 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/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com