簡體   English   中英

同時http post請求spring boot

[英]Simultaneous http post request spring boot

嗨,我有一個大小為 500k 的列表,我必須向帶有哈希參數的服務器發出請求。

服務器接受 200 個對象的 JSON 數組。 所以我每次可以發送 200 件物品。 但我仍然需要每次拆分列表並將該部分發送到服務器。

我有一個方法可以發出http post請求。 我想使用 spring 啟動選項(如果可用)來調用具有不同線程的方法並獲取響應並將它們合並為一個。

我使用沒有任何 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();
            }
        });

執行代碼后,您將獲得完成和未完成期貨的地圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM