2017-02-21 16 views
2

私は、ip/port情報と、リスト全体に送られなければならないメッセージを含むハッシュマップを持っています。 ハッシュマップとメッセージを受け取り、これを行う小さなメソッドを作成することにしました。これは次のようになります。NettyでいくつかのChannelFutureオブジェクトを連鎖させる方法は?

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の結果をどのように実装するかです。 私はChannelFuture-sを.sync()できますが、これは非同期ネットワーキングの目的に反するものです。

P .:本質的にここに記載されている機能をご希望の場合はhttps://twistedmatrix.com/documents/16.2.0/api/twisted.internet.defer.DeferredList.htmlですが、同等のものを見つけることができません。

答えて

0

一般的に、達成しようとしていることは実際には正しい非同期の方法ではありません。しかし、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を変更する必要がありますのでご注意ください。

+0

これは、実際にはこれが正しい非同期の方法ではないと言いました。それを行うには良いネットティ方法は何でしょうか? –

+0

私が意味することは、すべての書き込みを待つことは良い方法ではないということです。たぶんあなたはあなたのロジックについて考える必要があり、必要でないすべての書き込みを待っている代替案を検討する必要があります。 –

関連する問題