我对 Reactor (Spring5 WebClient) 很陌生,虽然我已经知道如何执行简单的请求并使用 map 或平面 map 处理其输出,但我现在需要做一些更困难的任务:
我有一个无法更改的端点。
此端点调用的基本签名是 Get
{host}/{endpointName}?System={1 到 3 的整数}&Form={1 到 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 的重试和重复机制,我只是不知道如何执行“使用不同请求参数的多次调用”部分。
这可能吗?
最佳答案
使用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... */)
如果我在上面的示例中计算的元组存储在 Map<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... */)
通过这些方法,您将永远不会离开函数世界,从而产生更干净、更简洁的代码。
关于spring-webflux - 如何使用 Reactor (Spring WebClient) 来模拟 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586820/