Java 如何用Netty链接多个未来对象?

Java 如何用Netty链接多个未来对象?,java,asynchronous,netty,Java,Asynchronous,Netty,我有一个包含ip/端口信息的hashmap和一条必须发送到整个列表的消息。 所以我决定创建一个接受hashmap和消息的小方法,并执行此操作。它看起来像这样: public static ChannelFuture sendMessageTo(Map<JsonElement, JsonObject> list, String message) { Set<JsonElement> keys = list.keySet(); for (Jso

我有一个包含ip/端口信息的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)
}
公共静态通道Future sendMessageTo(映射列表,字符串消息){
Set keys=list.keySet();
对于(JsonElement-key:keys){//遍历映射
ChannelInboundHandler[]处理程序={
新建MessageCompletenessHandler(),
新消息请求(消息),
};
JsonObject identity=list.get(key);
ChannelFuture f=connectWithHandler(identity.get(“ip”).getAsString(),identity.get(“port”).getAsInt(),handlers);//到以下ip/端口发送消息并返回ChannelFuture
}
return result;//此处result应该是一个ChannelFuture,当添加.addListener时,只有当for循环中的所有ChannelFuture-s都已完成时(即所有消息都已发送)才应调用它
}
评论应该足够清楚地解释情况。 问题是我如何实现这一未来结果。 我知道我可以用.sync()连接通道Future-s,但这违背了异步联网的目的


附言:我基本上想要这里描述的功能,但我找不到一个等效的功能。

一般来说,您试图实现的不是真正正确的异步方式。然而,netty有一个实用程序类来完成这类任务-。然而,它是包私有的,并且只用于真正实现代码中描述的功能的包。因此,您可以轻松复制此
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()) {
}
Collection futures=ArrayList();
...
//这是你的未来
ChannelFuture f=connectWithHandler(identity.get(“ip”).getAsString(),identity.get(“端口”).getAsInt(),handlers);
加入(f);
...
DefaultChannelGroupFuture groupOfFutures=新的DefaultChannelGroupFuture(期货,执行人);
if(groupOfFutures.sync().isSuccess()){
}

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

您说过这不是真正正确的异步方式。什么是好的方式呢?我的意思是——等待所有的写作不是一个好的方式。也许你需要考虑一下你的逻辑,并考虑在没有必要的时候等待所有的写作。