带有期货的Vertx中任意数量的看涨期权的顺序组成 [英] Sequential composition for arbitrary number of calls in Vertx with Futures

查看:79
本文介绍了带有期货的Vertx中任意数量的看涨期权的顺序组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中,我们在vertx中使用Futures:

We use Futures in vertx in examples like:

Future<JsonObject> fetchVehicle = getUserBookedVehicle(routingContext, client);

        fetchVehicle.compose(vehicleJson -> vehicleDoor(routingContext, client, vehicleJson, lock)).setHandler(
                asyncResult -> {
                    if (asyncResult.succeeded()) {
                    LOG.info("Door operation succeeded with result {}", asyncResult.result().encode());
                    handler.handle(Future.succeededFuture(new AsyncReply(200, "OK")));
                }
                else {
                    handler.handle(Future.failedFuture(asyncResult.cause()));
                }
        });

例如,我们处理2个呼叫.

where we handle 2 calls for example.

或者我还有另一个代码片段,可以处理任何数量的方法:

OR I have another snippet where I can handle any number of methods:

List<Future> futures = new ArrayList<>();
        conversation.getRequestList().forEach(req -> {
            Future<Message<Object>> senderFuture = Future.future();
            vertx.eventBus().send(AbstractOEMClientVerticle.ADDRESS, JsonObject.mapFrom(req), deliveryOptions, senderFuture.completer());

            // sent successfully. save the replyAddress and the conversation for later/callback
            log.info("Saving the conversation for the request.", conversation.getReplyAddress());
            pendingCommands.put(req.getBody().getString(MSG_ID), conversation);

            futures.add(senderFuture);
        });

        CompositeFuture.all(futures).setHandler(ar -> {
            if (ar.succeeded()) {
                handler.handle(Future.succeededFuture());
            } else {
                log.error("forwardToVWClient VW got result : {}", ar.cause());
                handler.handle(Future.failedFuture(ar.cause()));
            }
        });

在这里,我们正在链接conversation.getRequestList()中的所有请求,而无需事先知道它们的数量.

Here we are chaining all the requests in the conversation.getRequestList() without knowing their count in advance.

但是.all()方法的缺点是,我们无法控制订单.

But the shortcoming of .all() method is that, we have no control on the order.

如何与Vertx Futures链接任意数量的方法(不知道调用的确切数量)?

官方指南讨论顺序组成,但给出的示例有3个调用.它没有说明如何针对任意数量的呼叫执行此操作.

The official guide talks about sequential composition but the example given has 3 calls. It does not explain how to do it for arbitrary number of calls.

请参见 http://vertx.io/docs/vertx-core中的顺序构成" /java/

我希望这很清楚.

推荐答案

以下是使用map & reduce的解决方案,该解决方案以有序的方式执行方法,并以Future<String>

Here is a solution using map & reduce that executes a method in an orderly fashion and returns the accumulated result in the form of a Future<String>

 public static <T> Future<String> chainCall(List<T> list, Function<T, Future<String>> method){
        return list.stream().reduce(Future.succeededFuture(),// the initial "future"
                (acc, item) -> acc.compose(v -> method.apply(item)), // we return the compose of the previous "future" with "future" returned by next item processing
                (a,b) -> Future.future()); // not used! only useful for parallel stream.
    }

可以在以下示例中使用:

can be used as in the example below:

 chainCall(conversation.getRequestList(), this::sendApiRequestViaBus);

其中sendApiRequestViaBus是:

/**
     * @param request The request to process
     * @return The result of the request processing. 
     */
    Future<String> sendApiRequestViaBus(ApiRequest request) {
        Future<String> future = Future.future();
        String address = CommandUtilsFactory.getInstance(request.getImplementation()).getApiClientAddress();
        log.debug("Chain call start msgId {}", request.getId());

        vertx.eventBus().send(address, JsonObject.mapFrom(request), deliveryOptions, res -> {
            log.debug("Chain call returns {}", request.getId());
            if (res.succeeded()) {
                future.complete("OK");
            } else {
                future.fail("KO");
            }
        });
        return future;
    }

希望对您有帮助.

这篇关于带有期货的Vertx中任意数量的看涨期权的顺序组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆