0
嗨,我有一个大小为 500k 的列表,我必须使用哈希参数向服务器发出请求。

服务器接受 200 个对象的 JSON 数组。所以我每次可以发送 200 件物品。但我仍然需要每次拆分列表并将该部分发送到服务器。

我有一种方法可以发出http post请求。我想使用弹簧启动选项(如果可用)来调用具有不同线程的方法并获取响应并将它们合并为一个。

4

1 回答 1

0

我使用没有任何 springboot 标签的 java CompletableFuture 类做到了。但是您也可以将@async 用于您的方法。示例代码:

        var futures = new ArrayList<CompletableFuture<List<Composite>>>();
        var executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        for (List<CompositeRecord> records : Lists.partition(recordsList, 200)) {
            var future = CompletableFuture.supplyAsync(() -> /* call your method here */, executor);
            futures.add(future);
            Thread.sleep(2000);
        }

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).exceptionally(ex -> null).join(); // avoid throwing an exception in the join() call
        var futureMap = futures.stream().collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally));
        var compositeWithErrorList = new ArrayList<Composite>();
        futureMap.get(false).forEach(l -> {
            try {
                compositeWithErrorList.addAll(l.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });

执行代码后,您将拥有一张已完成和未完成期货的地图。

于 2020-12-07T08:52:53.427 回答