美文网首页
Netty EventLoop

Netty EventLoop

作者: 怖呆 | 来源:发表于2019-11-25 14:48 被阅读0次

EvnetLoop 是一个接口,是Netty 框架中组件之一,主要作用是将Channel 注册到本身,然后处理Channel的I/O操作。

关于Channel 的相关概念,请移步这里。

图一:EventLoop

通过图1我们发现EventLoop 本身非常的简单,只有一个parent 函数,大部分的函数都在EventExecutorGroup接口中,而EventExecutorGroup的大部分接口也仅仅是重写了父接口函数的返回值类型,EventExecutorGroup父接口都是Java API 的接口。如果你了解这些Java API接口,你就会发现EventLoop的主要函数如下:

  • ChannelFuture register(Channel)
  • EventLoopGroup parent()
  • EventExcutor next()

JavaDoc 描述

Will handle all the I/O operations for a Channel once registered. One EventLoop instance will usually handle more than one Channel but this may depend on implementation details and internals.

JavaDoc 翻译

Channel 注册到一个EventLoop,将会处理通道所有的I/O操作。一个EventLoop实例通常将处理多个Channel,但这可能取决于实现细节和内部。

一个EventLoop 实现类的例子

        final NioDatagramChannel channel = new NioDatagramChannel();
        NioEventLoopGroup group = new NioEventLoopGroup();
        group.register(channel); //将Channel 注册到EventLoop
        channel.pipeline().addLast(new SimpleChannelInboundHandler<io.netty.channel.socket.DatagramPacket>() {
            protected void channelRead0(ChannelHandlerContext ctx, io.netty.channel.socket.DatagramPacket msg) throws Exception {
                System.out.println(ByteBufUtil.hexDump(msg.content()));
            }
        });


        channel.bind(new InetSocketAddress(8887)).sync().channel().closeFuture().sync();

通过上面的例子,可以发现EventLoop 只使用一个register函数,这也是EventLoop的主要功能,一旦将Channel注册到EventLoop中,当Channel拥有I/O操作的时候,EventLoop 将会被调用。

当调用register被调用的时候,将会创建一个线程调用,这个线程会循环获取Channel中是否有I/O操作,当拥有I/O操作的时候,将会调用ChannelChannelPipeline中的ChannelHandler

图2:调用Handler

相关文章

网友评论

      本文标题:Netty EventLoop

      本文链接:https://www.haomeiwen.com/subject/bkrrwctx.html