Netty ChannelGroup

Posted 点滴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Netty ChannelGroup相关的知识,希望对你有一定的参考价值。

技术分享io.netty.channel.group.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 Channel can 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 ChannelGroup.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 ChannelInboundHandlerAdapter {
     @Override
     public void channelActive(ChannelHandlerContext ctx) {
         // closed on shutdown.
         allChannels.add(ctx.channel());
         super.channelActive(ctx);
     }
 }

以上是关于Netty ChannelGroup的主要内容,如果未能解决你的问题,请参考以下文章

Netty ChannelGroup

ChannelGroup和DefaultChannelGroup

Netty,并发 writeAndFlush

netty集群channel怎么跨集群

netty4在channel.writeAndFlush为啥还阻塞延迟

在 Netty5 中,如果我有 channelID 字符串,如何获取 Channel?