使用WebClient发送具有不同输入值的POST请求的最佳方式

问题描述 投票:0回答:1

我尝试使用 WebClient 通过在 POST 请求中以 JSON 字符串形式发送整数值来进行 API 调用。我有超过 100K 个值需要发送请求。

使用 WebClient 对象执行此操作的最佳方法是什么?

当我在单线程循环中调用 API 时,使用 WebClient 对象作为实例变量并为每次调用传递新的 JSON 字符串,这会花费大量时间。

使调用多线程是唯一的解决方案还是有什么方法可以使调用更高效?

java spring-boot spring-webflux reactive-programming project-reactor
1个回答
0
投票

您没有给出如何获取整数的任何详细信息,但这里有一个简单的示例来实现您想要的。

基本上,您应该将整数转换为

Flux
并使用
.flatMap()
异步发送每个请求并指定并发系数。从文档来看,并发因素是:

并发参数允许控制可以有多少个发布者 并行订阅和合并。反过来,该论点表明 向上游发出的第一个 Subscription.request 的大小。

代码如下所示:

/**
 * @param values List of integers
 * @param concurrency concurrency factor. Means how many requests to send at a time
 */
public void sendValues(List<Integer> values, Integer concurrency) {
    Flux.fromIterable(values)
            .flatMap(value -> sendRequest(value), concurrency) // set concurrency factor here
            // proceed with the response here
            .subscribe();
}

public Mono<String> sendRequest(Integer value) {
    return webClient.post()
            .uri("https://sendvalue.com")
            .bodyValue(String.valueOf(value))
            .retrieve()
            .bodyToMono(String.class) // map response body to String
            .doOnNext(__ -> log.info("Successfully sent {}", value)); 
}
© www.soinside.com 2019 - 2024. All rights reserved.