【问题标题】:Simultaneous http post request spring boot同时http post请求spring boot
【发布时间】:2021-03-06 00:56:57
【问题描述】:
你好,
我有一个大小为 500k 的列表,我必须使用哈希参数向服务器发出请求。
服务器接受 200 个对象的 JSON 数组。所以我每次可以发送 200 件物品。
但我仍然需要每次拆分列表并将该部分发送到服务器。
我有一个方法可以发出 http post 请求。我想使用 spring boot 选项(如果可用)来调用具有不同线程的方法并获取响应并将它们合并为一个。
【问题讨论】:
标签:
spring-boot
asynchronous
http-post
simultaneous-calls
【解决方案1】:
我使用没有任何 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();
}
});
代码执行后,您将拥有一张已完成和未完成的期货地图。