【问题标题】:How can i send a POST request from Java which is in for loop如何从 for 循环中的 Java 发送 POST 请求
【发布时间】:2018-06-11 22:40:21
【问题描述】:

我有一个循环向 URL 发送 POST 请求。 对于列表中的每个客户 ID,我都必须提出请求。 但这是按顺序进行的。 什么是让请求并行且更快的最佳方式。

我可以选择在数组中以 JSON 格式发送请求,但它给了我不希望的输出。

    for (int i = 0; i < Clients.clients.size(); i++){
         String itemIdHistory = URLResponseGetPost.postRequest(Resources.COMPANY_ZABBIX_URL, itemIdJsonResponse);
    }

【问题讨论】:

  • 1.这个问题与 JSON 无关(除非您在此处提供 JSON 如何产生影响) 2. 我看不出您的请求因不同的客户端而异。 3. URLResponseGetPost 似乎不是标准的东西。不知道它在内部做什么。根据您提供的内容,最简单的方法是 parallelStream,例如 clients.parallelStream().map(c -&gt; URLResponseGetPost.postRequest(blablabla)).collect(whateverCollectorSuitable);

标签: java json multithreading rest parallel-processing


【解决方案1】:

你应该看看ExecutorServicehttps://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html

这是一个例子:

ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 1";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 2";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 3";
    }
});

List<Future<String>> futures = executorService.invokeAll(callables);
for(Future<String> future : futures){
    System.out.println("future.get = " + future.get());
}
executorService.shutdown();

要并行运行,请考虑使用具有更多线程的线程池:https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-

【讨论】:

    猜你喜欢
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    相关资源
    最近更新 更多