Netty - EventLoopGroup

70 阅读1分钟

EventLoopGroup

EventLoopGroup 可以从类的继承关系中看出,其本质就是线程池
EventLoop 就是其中的线程,可以从EventLoopGroup.next()中获得
图片.png

与SocketChannel的绑定

当Server与Client之间建立一条连接后,会创建一条SocketChannel,将这条Channel交给EventLoopGroup中的一条EventLoop处理并与其绑定,之后若该Channel发生读写事件,都会由该EventLoop来进行处理

绑定关系如下:
Client1 -> Channel1 -> eventloop1
Client2 -> Channel2 -> eventloop2\

与ChannelHandler的绑定

在添加ChannelHandler时,可以使用下面代码的方法,为其指定一个EventLoopGroup,专门用于该Handler的执行。若不指定EventLoopGroup,则由当前Channel所绑定的EventLoop来进行处理

channel.pipeline()
        .addLast(eventLoopGroup1,name1,handler1)
        .addLast(eventLoopGroup2,name2,handler2);

该代码绑定关系如下:
Client1 -> Channel1 -> hander1-1 -> eventloop1-1
Client1 -> Channel1 -> hander1-2 -> eventloop2-1
Client2 -> Channel2 -> hander2-1 -> eventloop1-2
Client2 -> Channel2 -> hander2-2 -> eventloop2-2
其中handler后的编号代表(所属Channel编号)-(Handler类型)
其中eventloop后的编号代表(所属Group编号)-(Group中的Eventloop编号)

关闭EventLoopGroup

主线程执行完成时程序并不会结束,因为EventLoopGroup中的线程并未结束。此时可以调用EventLoopGroup.shutdownGraceFully()来优雅的结束。