【问题标题】:How does one go about chaining several ChannelFuture objects with Netty?如何使用 Netty 链接多个 ChannelFuture 对象?
【发布时间】:2017-07-11 04:23:27
【问题描述】:

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

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)
}

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

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

【问题讨论】:

    标签: java asynchronous netty


    【解决方案1】:

    一般来说,您想要实现的并不是真正正确的异步方式。然而,netty 有一个用于此类任务的实用程序类 - DefaultChannelGroupFuture.java。但是,它是包私有的,仅用于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。

    【讨论】:

    • 您说这不是真正正确的异步方式。什么是好的网络方式来做到这一点?
    • 我的意思是 - 等待所有写入不是一个好方法。也许您需要考虑您的逻辑并考虑无需等待所有写入的替代方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2020-03-16
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多