【问题标题】:How to use vertx in java to call api 4 times and then proceed如何在java中使用vertx调用api 4次然后继续
【发布时间】:2020-08-05 18:28:47
【问题描述】:
vertx.setPeriodic(1000, id -> {
    //api call
    if (count == 4){
        vertx.cancelTime(id); 
    }
});

现在的问题是我不想修复 1000 毫秒的时间,我只想调用 api 4 次,然后使用最终的 api 响应进行进一步处理,请帮助。

【问题讨论】:

    标签: java vert.x vertx-verticle


    【解决方案1】:

    一种方法是使用递归方法。

    因此,您可以实现这样的东西作为方便的入口点

    private Future<YourResultType> callApiNTimes(final int repetitions) {
        final Promise<YourResultType> p = Promise.promise();
    
        recursiveApiCalls(p, 0, repetitions);
    
        return p.future();
    }
    

    递归实现如下

    private void recursiveApiCalls(final Promise<YourResultType> p, final int counter, final int maxRepetitions) {
        yourRawApiCall().onComplete(reply -> {
            if (reply.failed()) {
                p.fail(reply.cause());
                return;
            }
    
            if (counter < maxRepetitions) {
                recursiveApiCalls(p, counter + 1, maxRepetitions);
                return;
            }
    
            p.complete(reply.result());
        });
    }
    

    最后实现yourRawApiCall,然后像这样使用它

    callApiNTimes(4).onComplete(reply -> {
        if (reply.failed()) {
            // Something went wrong, do your error handling..
            return;
        }
    
        final YourResultType result = reply.result();
    
        // Do something with your result..
    });
    

    另一种方法是将您的 API 调用作为期货放在一个列表中 并与CompositeFuture.allCompositeFuture.join、.. 并行执行此列表,而不是一个接一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      相关资源
      最近更新 更多