Netty ChannelGroup

ChannelGroup 分析

ChannelGroup 用来管理一组 Channel,我们可以很方便的对一组 Channel 做同样的操作。从类图关系来看,ChannelGroup本质上还是一个Set

ChannelGroup

1
ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

查看DefaultChannelGroup实现,我们添加Channel时都会注册一个事件,当Channel关闭后会自动把它从ChannelGroup删除掉。所以,我们只需要正常关闭Channel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private final ChannelFutureListener remover = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
remove(future.channel());
}
};

@Override
public boolean add(Channel channel) {
...
boolean added = map.putIfAbsent(channel.id(), channel) == null;
if (added) {
channel.closeFuture().addListener(remover);
}
...
}
本站采用「署名 4.0 国际」进行许可。