使用Spring WebFlux和WebClient替换传统的Java以循环逻辑为反应性编程
我正在将Spring Boot(MVC)应用程序转换为反应性编程(Spring WebFlux),
用于进行外部休息,我正在使用WebClient。
List<String> targetUrls = Arrays.asList("one","two","three");
int iteration = 1;
for(String target:targetUrls){
// make a rest call here
// if 200 break the loop
// else loop continues
}
其余的电话在这里返回单声道。
是否有一种方法可以迭代URL列表(在这种情况下)并根据
单声道上尝试过的flatmap响应打破循环,并且基于响应可以对另一个URL进行休息 - &gt;如果我们事先知道URL的数量,这起作用了
I'm converting Spring Boot (MVC) application to Reactive Programming (Spring Webflux)
For making external rest calls, I'm using WebClient.
List<String> targetUrls = Arrays.asList("one","two","three");
int iteration = 1;
for(String target:targetUrls){
// make a rest call here
// if 200 break the loop
// else loop continues
}
The rest call here returns a Mono.
Is there a way to iterate over the list of urls(here in this case) and break the loop based on some response
Tried flatMap on the Mono and based on response can make a rest call to another url --> This works in case we know before hand the number of urls
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您是如何从WebClient调用URL的,但是仅假设URL传递给方法
webclient.get.get(String url)
,我将继续使用该示例。这些步骤将有点像您首先获得URL的通量,然后使用
flatmap
(因为您的响应是单声道),然后在这些上使用map
。现在,您应该有很多回应。如果WebClient的错误处理还不够,您也可以插入之间的某些内容。
I'm not sure how you call the urls from the WebClient, but just assuming the URLs are passed to a method
WebClient.get(String url)
, I will continue with the example.The steps would be somewhat like you will first get a Flux of the URLs, then use
flatMap
(because your response is a Mono), then usemap
on these.Now you should have a Flux of responses. If the error handling from the WebClient isn't enough, you can also insert something inbetween.
您可以使用几种模式来实现此逻辑,
您可以使用
flatmap
同时执行多个查询。默认情况下,flatmap
将处理queues.small_buffer_size = 256
机上内部序列的数字。您可以控制并发
flatmap(url - &gt; webclient.get(url),并发)
,或使用concatmap
操作员(如果要顺序执行查询)。另一个有用的模式,如果您需要响应才能做出有关下一个请求的决定 - 使用
展开
操作员。例如,如果有分页的请求。There are several patterns you could apply to implement this logic
You can use
flatMap
to execute multiple queries concurrently. By default,flatMap
will processQueues.SMALL_BUFFER_SIZE = 256
number of in-flight inner sequences.You could control concurrency
flatMap(url -> webClient.get(url), concurrency)
or useconcatMap
operator if you want to execute queries sequentially.Another useful pattern in case you need response to make decision about next request - use
expand
operator. For example, in case of paginated requests.