首页 > 解决方案 > 如何使用 Reactor (Spring WebClient) 模拟 for 循环

问题描述

我对 Reactor (Spring5 WebClient) 很陌生,虽然我已经知道如何做简单的请求并使用 map 或 flatmap 处理它的输出,但我现在需要做一些更难的任务:

我有一个无法更改的端点。

此端点调用的基本签名是 Get {host}/{endpointName}?System={integer from 1 to 3}&Form={integer from 1 to 5}

我需要反复调用它并处理这对的输出:

{1, 1},
{1, 2},
{1, 3},
{1, 4},
...
{3, 2},
{3, 4},
{3, 5}

对于一个请求,例如:

WebClient.create().get()
  .uri(uri -> uri.scheme("http")
    .host(myHost)
    .path(myPath)
    .queryParam("System", 1)
    .queryParam("Form", 1)
    .build())
  .exchange()
  .flatMap(response -> {
   //process response and produce desired output
   });

我尝试做的是: 1. 发出多个请求(基本上迭代包含上述所有对的映射) 2. 处理每个请求结果(处理结果添加到 WebClient 之前创建的 json 数组) 3. 当所有请求制作 - 给出“组合输出”。

示例:如果请求与组合 1,1 给出

[
{
"Name":"John",
"Surname":"Doe"
}
]

第 3、5 对给出

[
{
"Name":"Jane",
"Surname":"Dean"
}
]

此 WebClient 调用的结果应该是

[
{
"Name": "John",
"Surname: "Doe"
},
....
{
"Name": "Jane",
"Surname": "Dean"
}
]

我知道 Mono 的重试和重复机制,我只是不知道如何执行“具有不同请求参数的多个调用”部分。

这甚至可能吗?

标签: spring-webfluxproject-reactor

解决方案


Flux.range结合使用flatMap


Flux.range(1, 5)
    .flatMap(i -> Flux.range(1, 5).map(j -> Tuples.of(i, j)))
    .flatMap(t ->
        WebClient.create().get()
            .uri(uri -> uri.scheme("http")
                .host(myHost)
                .path(myPath)
                .queryParam("System", t.getT1())
                .queryParam("Form", t.getT2())
                .build())
            .exchange()
    )
    .flatMap(response -> /* Handle the response... */)

如果我在上面示例中计算的元组改为存储在 aMap<Integer, Integer>中,则必须稍微更改代码:


Flux.fromIterable(intIntMap.entrySet())
    .flatMap(entry ->
        WebClient.create().get()
            .uri(uri -> uri.scheme("http")
                .host(myHost)
                .path(myPath)
                .queryParam("System", entry.getKey())
                .queryParam("Form", entry.getValue())
                .build())
            .exchange()
    )
    .flatMap(response -> /* Handle the response... */)

使用这些方法,您将永远不会离开函数世界,从而获得更干净、更简洁的代码。


推荐阅读