我对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.发出多个请求(基本上遍历地图tha包含上述所有对) 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的重试和重复机制,我只是不知道如何执行“具有不同请求参数的多次调用”部分。
这有可能吗?
答案 0 :(得分:1)
将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... */)
使用这些方法,您将永远不会离开功能世界,从而获得一段更简洁明了的代码。