Netty源码三:NioEventLoop创建与run方法

1.入口

image.png
会调用到父类SingleThreadEventLoop的构造方法

2.SingleThreadEventLoop

image.png
继续调用父类SingleThreadEventExecutor的构造方法

3.SingleThreadEventExecutor

image.png
到这里完整的总结一下:

  1. 将线程执行器保存到每一个SingleThreadEventExcutor里面去
  2. 创建了MpscQueue,具体为什么,因为在NioEventLoop里面重写了newTaskQueue方法

image.png

  1. 等父类调用完毕,最后回到NioEventLoop里面,最重要的一件事:创建Selector

最后那一张图完整的总结一下:
image.png

4.NioEventLoop.run

4.1 调用入口

这里还是要回顾一下这个方法是什么时候调用的?
Netty在启动的时候,在调用config().group().register(channel) ,使用bossGroup做channel注册的时候,它会使用EventExecutorChooser找一个NioEventLoop然后去做注册,最终会调用到这个abstractChannel.register方法
image.png
一般来说,我们启动的时候,运行到这里,eventLoop会返回false,所以会调用到eventLoop.execute里面的方法,在这里我们就能找到这个NioEventLoop.run的调用地方
image.png
image.png
image.png
也就说在使用NioEventLoop将channel注册到selector的时候,会判断是不是eventloop线程调用,如果不是就会使用SingleThreadEventExecutor.execute执行,它会将NioEventLoop.run方法包装成一个runnable,然后创建一个线程并启动,然后就调用到NioEventLoop里面了

4.2 run方法


/*** todo select()                    检查是否有IO事件* todo ProcessorSelectedKeys()     处理IO事件* todo RunAllTask()                处理异步任务队列*/
@Override
protected void run() {for (; ; ) {try {// todo hasTasks() true代表 任务队列存在任务switch (selectStrategy.calculateStrategy(selectNowSupplier, hasTasks())) {case SelectStrategy.CONTINUE:continue;case SelectStrategy.SELECT:// todo 轮询IO事件, 等待事件的发生, 本方法下面的代码是处理接受到的感性趣的事件, 进入查看本方法select(wakenUp.getAndSet(false));// wakenUp.compareAndSet(false, true)' is always evaluated// before calling 'selector.wakeup()' to reduce the wake-up// overhead. (Selector.wakeup() is an expensive operation.)//// However, there is a race condition in this approach.// The race condition is triggered when 'wakenUp' is set to// true too early.//// 'wakenUp' is set to true too early if:// 1) Selector is waken up between 'wakenUp.set(false)' and//    'selector.select(...)'. (BAD)// 2) Selector is waken up between 'selector.select(...)' and//    'if (wakenUp.get()) { ... }'. (OK)//// In the first case, 'wakenUp' is set to true and the// following 'selector.select(...)' will wake up immediately.// Until 'wakenUp' is set to false again in the next round,// 'wakenUp.compareAndSet(false, true)' will fail, and therefore// any attempt to wake up the Selector will fail, too, causing// the following 'selector.select(...)' call to block// unnecessarily.//// To fix this problem, we wake up the selector again if wakenUp// is true immediately after selector.select(...).// It is inefficient in that it wakes up the selector for both// the first case (BAD - wake-up required) and the second case// (OK - no wake-up required).if (wakenUp.get()) {selector.wakeup();}// fall throughdefault:}cancelledKeys = 0;needsToSelectAgain = false;final int ioRatio = this.ioRatio;  // todo 默认50// todo  如果ioRatio==100 就调用第一个     processSelectedKeys();  否则就调用第二个if (ioRatio == 100) {try {// todo 处理 处理发生的感性趣的事件processSelectedKeys();} finally {// Ensure we always run tasks.// todo 用于处理 本 eventLoop外的线程 扔到taskQueue中的任务runAllTasks();}} else {// todo 因为ioRatio默认是50 , 所以来else// todo 记录下开始的时间final long ioStartTime = System.nanoTime();try {// todo 处理IO事件processSelectedKeys();} finally {// Ensure we always run tasks.// todo  根据处理IO事件耗时 ,控制 下面的runAllTasks执行任务不能超过 ioTime 时间final long ioTime = System.nanoTime() - ioStartTime;// todo 这里面有聚合任务的逻辑runAllTasks(ioTime * (100 - ioRatio) / ioRatio);}}} catch (Throwable t) {handleLoopException(t);}// Always handle shutdown even if the loop processing threw an exception.try {if (isShuttingDown()) {closeAll();if (confirmShutdown()) {return;}}} catch (Throwable t) {handleLoopException(t);}}}


这里注释其实说得挺清楚,最后总结一下:

  1. select(wakenUp.getAndSet(false)):轮训io事件发生,当timeout或者有事件会break
  2. processSelectedKeys:处理io事件
  3. 运行taskQueue里面的任务

4.3 processSelectedKeys

在真正执行的时候,最终会走到processSelectedKeysOptimized,netty对底层selectKeys容器进行过优化,用数组代替了keyset
image.png

这里我为了debug,使用telnet localhost 8899, 接着就会进入到processSelectedKeysOptimized中
image.png
在走进processSelectedKey方法之后,最终会走到unsafe.read方法
image.png
image.png

5.AbstractNioMessageChannel

image.png
接着会调用到子类NioServerSocketChannel的doReadMessage(readBuf), 调用完子类之后,会通过pipline.fireChannelRead, 意思就是对于server端来说可读了,但是注意这时候传的是子类中创建的NioSocketChannel,说白了给server端一个NioSocketChannel,就是要创建新连接了。最终会调用到ServerBootstrapAcceptor的ChannelRead,具体看后面的ServerBootStrapAcceptor类
image.png

6.NioServerSocketChannel

image.png
这里主要做了几件事:

  1. SocketUtils.accpet接受连接,并创建jdk底层的socketChannel
  2. new NioSocketChannel:将jdk封装成NioSocketChannel,这里和创建NioServerSocketChannel的时候一样,不断的调用父类,同时创建NioServerChannel的pipline,!!!这里注意,这里会设置感兴趣的事件为read

image.png

7.ServerBootstrap#ServerBootstrapAcceptor

ServerBootstrapAcceptor是ServerBootstrap的内部类
之前AbstractNioMessageChannel里面的image.png,最终会调用到ServerBootstrapAcceptor的channelRead方法
image.png
简单的总结一下做了几件事:

  1. 给sockeChannel(也是这里的child)设置childHandler
  2. 使用childGroup.register 来完成socketChannel到Selector的注册,这里和SocketServerChannel到Selector的注册逻辑是一样的,都是从EventLoopGroup中选一个EventLoop(里面有Selector),然后调用jdk的register(eventloop.getSelector, 0, NioSocketChannel(netty对于socketChannel的包装))

8.AbstractChannel

childGroup.register -> MultithreadEventLoopGroup.register -> SingleThreadEventLoop.register -> AbstractChannel.register
image.png
image.png
AbstractChannel.abstractUnsafe.register
image.png
这一刻代码之前都讲过,就是把创建socketChannel注册到EventLoop上的Selector上去
AbstractChannel.register0():
image.png

  1. doRegister: 完成了SocketChannel到Selector的注册
  2. pipeline.invokeHandlerAddedIfNeeded: 这里会调用之前我们设置MyServerInitializer.initChannel(), 会往SocketChannel的pipeline中加入一系列读写用到的Handler

9.总结

最后那一张图总结一下:
image.png


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/441146.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Windows断开映射磁盘提示“此网络连接不存在”,并且该磁盘直在资源管理器中

1、打开注册表编辑器 快捷键winR 打开“运行”, 输入 regedit 2、 删除下列注册表中和无法移除的磁盘相关的选项 \HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\ 3、打开“任务管理器”,重新启动“Windows资源…

微信扫码登录流程

微信官方文档使用 搜索“微信开放平台”点击导航栏的“资源中心”点击“网站应用”下的“微信登录功能”地址微信扫码登录是基于OAuth2的,所以需要第三方应用(就是实现微信扫码登录的应用)成为微信的客户端,获取AppId和AppSecret…

用AI工具一键生成原创文案的方法

一键生成原创文案对于文案工作者来说它是一种高效率创作文案内容的方法。文案工作者知道创作文案是一件消耗精力和时间的事情,遇到没有创作灵感,想要写一篇高质量的文案内容简直难上加难,因此,互联网上出现了一键生成原创文案的方…

漏洞原理文件上传漏洞

一 文件上传漏洞介绍(理论) 文件上传漏洞是一种常见的web应用程序漏洞,允许攻击者向服务器上传恶意文件。这种漏洞可在没有恰当的安全措施的情况下,将任意类型的文件上传到服务器上,从而可能导致以下安全问题&#xff…

【云原生】docker-compose单机容器编排工具

目录 什么是docker-compose? 管理区别 docker-compose的三大概念 YAML 文件格式及编写注意事项 使用 YAML 时需要注意下面事项: 布尔值类型 字符串类型 一个key有多个值 对象object类型 文本块 锚点 docker-compose配置模板文件常用的字段 …

【electron】安装网络问题处理

目录 场景排查问题排查结论electron 安装失败解决方案 新的问题electron-builder 打包失败处理 场景 在mac上使用electron进行代码开发的时候,无法正常下载与electron、electron-builder相关的依赖 排查问题 是不是因为没有翻墙导致资源无法下载是不是没有设置正…

【网络基础】IP

IP协议报头 4位版本号(version): 指定IP协议的版本, 对于IPv4来说, 就是4.4位头部长度(header length): IP头部的长度是多少个32bit, 也就是 length * 4 的字节数. 4bit表示最大的数字是15, 因此IP头部最大长度是60字节. 8位服务类型(Type Of Service): 3位优先权字段(已经弃用…

Qt/C++音视频开发64-共享解码线程/重复利用解码/极低CPU占用/画面同步/进度同步

一、前言 共享解码线程主要是为了降低CPU占用,重复利用解码,毕竟在一个监控系统中,很可能打开了同一个地址,需要在多个不同的窗口中播放,形成多屏渲染的效果,做到真正的完全的画面同步,在主解码…

如何理解汽车诊断中的,诊断故障代码DTC

DTC(Diagnostic Trouble Code)全称诊断故障代码,是汽车诊断中非常重要的一个分支技术。也可以说是非常重要的组成部分。在uds 诊断和OBD诊断都是不可或缺的组成部分。充分理解DTC对于汽车开发过程也是必不可少的。 本文主要说明UDS下的诊断故障代码,即理…

前端颜料盘??

前端颜料盘&#xff1f;&#xff1f; 一、原生颜料盘 <input type"color" placeholder"选择颜色">二、第三方开源库 Pickr&#xff1a; GitHub: https://github.com/Simonwep/pickr官方网站: https://simonwep.github.io/pickr/Pickr 是一个轻量级…

awk 文本处理工具三剑客

一、什么是awk 1.1 awk 基本概念 awk&#xff08;语言&#xff09;&#xff1a; 读取一行处理一行 是一个功能强大的编辑工具&#xff0c;逐行读取输入文本&#xff0c;默认以空格或tab键作为分隔符作为分隔&#xff0c;并按模式或者条件执行编辑命令。而awk比较倾向于将一行…

第九节HarmonyOS 常用基础组件19-CheckboxGroup

1、描述 多选框群组&#xff0c;用于控制多个选框全选或者全不选状态。 2、接口 CheckboxGroup(options?: {group?: string}) 3、参数 参数名 参数类型 必填 描述 group string 否 群组名称 4、属性 selectAll - boolean - 设置是否全选&#xff0c;默认值&…