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

2024-01-31 20:20

本文主要是介绍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


这篇关于Netty源码三:NioEventLoop创建与run方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/664954

相关文章

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤

在Golang中实现定时任务的几种高效方法

《在Golang中实现定时任务的几种高效方法》本文将详细介绍在Golang中实现定时任务的几种高效方法,包括time包中的Ticker和Timer、第三方库cron的使用,以及基于channel和go... 目录背景介绍目的和范围预期读者文档结构概述术语表核心概念与联系故事引入核心概念解释核心概念之间的关系

在Linux终端中统计非二进制文件行数的实现方法

《在Linux终端中统计非二进制文件行数的实现方法》在Linux系统中,有时需要统计非二进制文件(如CSV、TXT文件)的行数,而不希望手动打开文件进行查看,例如,在处理大型日志文件、数据文件时,了解... 目录在linux终端中统计非二进制文件的行数技术背景实现步骤1. 使用wc命令2. 使用grep命令

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到

python如何创建等差数列

《python如何创建等差数列》:本文主要介绍python如何创建等差数列的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python创建等差数列例题运行代码回车输出结果总结python创建等差数列import numpy as np x=int(in

XML重复查询一条Sql语句的解决方法

《XML重复查询一条Sql语句的解决方法》文章分析了XML重复查询与日志失效问题,指出因DTO缺少@Data注解导致日志无法格式化、空指针风险及参数穿透,进而引发性能灾难,解决方案为在Controll... 目录一、核心问题:从SQL重复执行到日志失效二、根因剖析:DTO断裂引发的级联故障三、解决方案:修复