一、Netty源码分析
https://github.com/netty/netty/tree/4.1/example/src/main/java/io/netty/example/echo
上找到echo这个example
1.1 服务端启动流程
1.1.1 两个NioEventLoopGroup
服务端代码首先要定义两个NioEventLoopGroup,打个断点进去
![image-20220325200803748](http://img.banditblog.top/typora/202203272110879.png)
NioEventLoopGroup继承MultithreadEventLoopGroup,加载的时候执行父类静态方法,初始化DEFAULT_EVENT_LOOP_THREADS = cpu核数 * 2
![image-20220325201052312](http://img.banditblog.top/typora/202203272110881.png)
如果是无参构造就让默认children线程为12个,而bossgroup是有参,只有1个线程,workergroup就是12个线程。这些线程就是事件循环组
![image-20220325201358502](http://img.banditblog.top/typora/202203272110882.png)
这个过程中还会生成一个Selector多路复用器的Provider,供之后生成Selector使用,是由操作系统决定的,Windows下就是WindowsSelectorProvider
![image-20220325202422160](http://img.banditblog.top/typora/202203272110883.png)
这个位置就是生成children线程的地方,生成完之后为每个线程加上结束回调监听器
![image-20220325201925903](http://img.banditblog.top/typora/202203272110884.png)
![image-20220325203150711](http://img.banditblog.top/typora/202203272110885.png)
1.1.2 ServerBootStrap
接下来在ServerBootStrap那打个断点
![image-20220325203356933](http://img.banditblog.top/typora/202203272110886.png)
进去看看,加载ServerBootstrap会先加载AbstractBootstrap,声明了一堆变量,实际上都没初始化,留给后面链式编程添加属性
![image-20220325204818583](http://img.banditblog.top/typora/202203272110887.png)
然后针对链式编程进行断点研究
![image-20220325205015134](http://img.banditblog.top/typora/202203272110888.png)
group(bossGroup,workerGroup)
:将bossgroup赋给group,workergroup赋给childgroup
![image-20220325205152428](http://img.banditblog.top/typora/202203272110889.png)
channel(NioServerSocketChannel.class)
:用反射创建一个ChannelFactory,为之后创建NioServerSockerChannel提供一个工厂
![image-20220325205545132](http://img.banditblog.top/typora/202203272110890.png)
option(ChannelOption.SO_BACKLOG, 100)
:添加一些TCP参数,可以看到是放进options这个Li