简体   繁体   English

如何使用Reactor(Spring WebClient)进行重复调用?

[英]How to use Reactor (Spring WebClient) to do a repeat call?

I am using Reactor (Spring5 WebClient) as my reactive programming API. 我使用Reactor(Spring5 WebClient)作为我的反应式编程API。 I have 2 REST endpoint to call. 我有2个REST端点可以调用。 The result of the first one will be the parameter to the second one. 第一个的结果将是第二个的参数。 For the second API, it will return a result with "hasMore" value. 对于第二个API,它将返回带有“hasMore”值的结果。 If this value is true , I should change the pagination parameters and call the second API again. 如果此值为true ,我应该更改分页参数并再次调用第二个API。 The demo code is the following: 演示代码如下:

 client.getApi1()
        .map(r -> r.getResult())
        .flatMap(p -> client.getApi2(p, 2(page size), 1(page start)))
        .subscribe(r -> System.out.println(r.isHasmore()));

How to repeat calling the second API (getApi2) until "hasMore" is false. 如何重复调用第二个API(getApi2)直到“hasMore”为false。

Besides, I need to change the parameters page size and page start 此外,我需要更改参数页面大小和页面开始

Try this code: 试试这段代码:

 AtomicInteger pageCounter = new AtomicInteger(0);
 client.getApi1()
    .map(r -> r.getResult())
    .flatMap(p -> client.getApi2(p, 2(page size), pageCounter.incrementAndGet()))
    .repeat()            
    .takeWhile(r -> r.isHasmore())
    .subscribe(r -> System.out.println(r.isHasmore()));

repeat() calls getApi2 infinitely. repeat()无限调用getApi2 takeWhile(continuePredicate) relays values while a continuePredicate ( r.isHasmore() ) returns true takeWhile(continuePredicate)continuePredicate( r.isHasmore()返回true时中继值

I find a solution by use expand operator. 我通过使用expand运算符找到了解决方案。 But, need to do some change on my API call. 但是,需要对我的API调用进行一些更改。 The response from the getApi2 need to return last page size and last page start. getApi2的响应需要返回最后一页的大小和最后一页的开始。

    client.getApi1()
        .map(r -> r.getResult())
        .getApi2(p, 2, 1)
        .expand(res -> {
            if (res.isHasmore()) {
                return client.getApi2(orgId, res.getPageSize(), res.PageStart() + 1);
            }
            return Flux.empty();
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM