Netty的EventLoopGroup组件
2026/9/27大约 2 分钟
调用 group() 可以设置线程组,该线程组其实就是 Reactor 的线程组,我们知道 Netty 是基于 Reactor 模式的,group() 就是设置 Reactor 模式的线程组,Reactor 模式,线程组有两个:
- BossGroup:服务器连接监听线程组,该线程组专门用来处理客户端的连接请求。
- WorkGroup:工作线程组,即业务处理线程组,用来处理每一条连接的数据收发的线程组。
一、EventLoop
EventLoopGroup 就是一组 EventLoop,EventLoop 从字面上来看就是 event + loop,也就是事件循环。事件就是 I/O 事件,循环则可以理解为while(true), EventLoop的继承关系:
public interface EventLoop extends OrderedEventExecutor, EventLoopGroup
public interface EventLoopGroup extends EventExecutorGroup
public interface EventExecutorGroup extends ScheduledExecutorServiceScheduledExecutorService是JUC并发包的类型,所 EventLoop 本质就是一个单线程执行器:
@Slf4j
public class TestMain {
public static void main(String[] args) throws Exception {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
EventLoop eventLoop = eventLoopGroup.next();
eventLoop.next().submit(()->{
log.info("theadName1:{}", Thread.currentThread().getName());
});
}
}结果:
15:56:47.782 [nioEventLoopGroup-1-1] INFO top.zouyh.TestMain - theadName1:nioEventLoopGroup-1-1EventLoop 本质就是一个单线程执行器,能用来干什么呢?当客户端与服务端建立连接后,服务端会创建一个 Channel,并将该 Channel 与 EventLoop 绑定。绑定后,该 Channel 在整个生命周期内所有发生的事件都由该 EventLoop 来处理,一个 EventLoop 可以绑定多个 Channel 。对于 EventLoop 而言,它就是通过不断循环它所绑定的 Channel 事件列表,检测是否有事件发生,如果有,则将该事件分发给 worker 线程处理。
二、EventLoopGroup
EventLoopGroup 就是一组 EventLoop ,它主要是来维护和管理 EventLoop,一般我们是不会直接使用 EventLoop 的,而是通过 EventLoopGroup 来使用它。我们看 EventLoopGroup 的源码就知道 EventLoopGroup 就提供了两个方法:
public interface EventLoopGroup extends EventExecutorGroup {
// 按照顺序的方式返回 EventLoop
EventLoop next();
// 并将该 Channel 与 EventLoop 绑定
ChannelFuture register(Channel var1);
ChannelFuture register(ChannelPromise var1);
/** @deprecated */
@Deprecated
ChannelFuture register(Channel var1, ChannelPromise var2);
}next方法案例:
public class TestMain {
public static void main(String[] args) throws Exception {
// 创建两个线程
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2);
log.info("{}",eventLoopGroup.next());
log.info("{}",eventLoopGroup.next());
log.info("{}",eventLoopGroup.next());
log.info("{}",eventLoopGroup.next());
}
}结果:
16:18:19.906 [main] INFO top.zouyh.TestMain - io.netty.channel.nio.NioEventLoop@7bb58ca3
16:18:19.907 [main] INFO top.zouyh.TestMain - io.netty.channel.nio.NioEventLoop@c540f5a
16:18:19.907 [main] INFO top.zouyh.TestMain - io.netty.channel.nio.NioEventLoop@7bb58ca3
16:18:19.907 [main] INFO top.zouyh.TestMain - io.netty.channel.nio.NioEventLoop@c540f5a