netty-ChannelGroup

public interface ChannelGroupextends Set<Channel>, Comparable<ChannelGroup>

A thread-safe Set that contains open Channels and provides various bulk operations on them. Using ChannelGroup, you can categorize Channels into a meaningful group (e.g. on a per-service or per-state basis.) A closed Channel is automatically removed from the collection, so that you don't need to worry about the life cycle of the added Channel. A Channelcan belong to more than one ChannelGroup.

Broadcast a message to multiple Channels

If you need to broadcast a message to more than one Channel, you can add the Channels associated with the recipients and call write(Object):

 ChannelGroup recipients =
         new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
 recipients.add(channelA);
 recipients.add(channelB);
 .. recipients.write(Unpooled.copiedBuffer(
         "Service will shut down for maintenance in 5 minutes.",         CharsetUtil.UTF_8));

Simplify shutdown process with ChannelGroup

If both ServerChannels and non-ServerChannels exist in the same ChannelGroup, any requested I/O operations on the group are performed for the ServerChannels first and then for the others.

This rule is very useful when you shut down a server in one shot:

 ChannelGroup allChannels =
         new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

 public static void main(String[] args) throws Exception {     ServerBootstrap b = new ServerBootstrap(..);
     ...
     b.childHandler(new MyHandler());

     // Start the server
     b.getPipeline().addLast("handler", new MyHandler());     Channel serverChannel = b.bind(..).sync();     allChannels.add(serverChannel);

     ... Wait until the shutdown signal reception ...

     // Close the serverChannel and then all accepted connections.     allChannels.close().awaitUninterruptibly();
 }

 public class MyHandler extends ChannelHandlerAdapter {     @Override
     public void channelActive(ChannelHandlerContext ctx) {
         // closed on shutdown.         allChannels.add(ctx.channel());
         super.channelActive(ctx);
     }
 }


转载于:https://my.oschina.net/u/131940/blog/632752

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值