如何使用 Netty 链接多个 ChannelFuture 对象?

How does one go about chaining several ChannelFuture objects with Netty?

我有一个哈希图,其中包含 ip/port 信息和一条必须发送到整个列表的消息。 所以我决定创建一个小方法来接受散列图和消息并执行此操作。它看起来像这样:

public static ChannelFuture sendMessageTo(Map<JsonElement, JsonObject> list, String message) {
        Set<JsonElement> keys = list.keySet();
        for (JsonElement key : keys) { //iterate through the map
            ChannelInboundHandler[] handlers = {
                    new MessageCompletenessHandler(),
                    new MessageRequest(message),
            };
            JsonObject identity = list.get(key);
            ChannelFuture f = connectWithHandler(identity.get("ip").getAsString(), identity.get("port").getAsInt(), handlers); //to the following ip/port send message and return ChannelFuture
        }
        return result; //here result should be a ChannelFuture that when .addListener is added it should be called only when ALL the ChannelFuture-s from the for loop have finished(a.k.a. all messages have been sent)
}

评论应该把情况说清楚了。 问题是我如何实现这个 ChannelFuture 结果。 我知道我可以 .sync() ChannelFuture-s,但这违背了异步网络的目的。

P.S.: 我本质上想拥有此处描述的功能 https://twistedmatrix.com/documents/16.2.0/api/twisted.internet.defer.DeferredList.html 但我找不到等效项。

总的来说,您想要实现的并不是真正正确的异步方式。然而,netty 有一个实用程序 class 用于此类任务 - DefaultChannelGroupFuture.java. However it is package private and used only for DefaultChannelGroup.java 确实可以执行您在代码中描述的操作。所以你可以很容易地复制这个 DefaultChannelGroupFuture 并使用它。更具体地说:

Collection<ChannelFuture> futures = ArrayList<ChannelFuture>();
...
 //here you add your futures
 ChannelFuture f = connectWithHandler(identity.get("ip").getAsString(), identity.get("port").getAsInt(), handlers); 
 futures.add(f);
...

DefaultChannelGroupFuture groupOfFutures = new DefaultChannelGroupFuture(futures, executor);
if (groupOfFutures.sync().isSuccess()) {
}

请记住,您需要根据需要更改 DefaultChannelGroupFuture。