前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Netty组件之Channel注册

Netty组件之Channel注册

作者头像
瓜农老梁
发布2020-07-22 15:32:39
4850
发布2020-07-22 15:32:39
举报
文章被收录于专栏:瓜农老梁瓜农老梁

前言

本文将分析EventLoopGroup初始化、EventLoop的选择策略以及Channel是如何通过EventLoop注册到Selector上的。

一、EventLoopGroup类图概览

在客户端示例代码中的中实例化了NioEventLoopGroup,接下来分析下该实例化过程。

EventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(workerGroup); 

从以下类图结构io.netty.util.concurrent.AbstractEventExecutorGroup分支主要负责多线程任务的处理;io.netty.channel.EventLoopGroup分支主要负责Channel相关的注册。MultithreadEventExecutorGroup与MultithreadEventLoopGroup分别继承和实现了上面AbstractEventExecutorGroup和EventLoopGroup,将其负责的功能进行融合。

二、构造函数解读

构造函数 nThreads:eventLoopThreads线程数量,默认值0时取CPU核数的2倍,可以通过参数io.netty.eventLoopThreads指定 Executor:默认ThreadPerTaskExecutor SelectorProvider默认SelectorProvider.provider(),用于开启Selector和Channel SelectStrategyFactory:SelectStrategy工厂类,默认DefaultSelectStrategyFactory EventExecutorChooserFactory:EventExecutor选择器,默认为DefaultEventExecutorChooserFactory

三、初始化EventExecutor数组

代码解读 EventExecutor[] children:数组大小为nThreads,默认为CPU核数乘以2。 EventExecutor继承了EventExecutorGroup本质上为线程框架类Executor children[i]:数据元素为EventLoop,本示例中为NioEventLoop。

NioEventLoop类图

NioEventLoop继承了SingleThreadEventLoop,SingleThreadEventLoop同时继承和实现了EventExecutor和EventLoop。即:NioEventLoop拥有了线程类框架处理多线程任务的能力和处理Channel能力。

备注:本文中EventExecutor数组children的元素为NioEventLoop,NioEventLoop同时拥有线程框架能力和Channel注册等处理能力。

四、EventExecutor选择器

第三部分对EventExecutor[] children进行初始化分析,然在使用时如何选择其中一个元素呢? 在初始化过程中有以下一行代码,用于初始化EventExecutorChooser。

chooser = chooserFactory.newChooser(children);

EventExecutorChooser类图结构

选择策略

@1 如果数组长度是2的幂次方,选择PowerOfTwoEventExecutorChooser,在选取EventExecutor时使用executors[idx.getAndIncrement() & executors.length - 1] @2 如果数组长度不是2的幂次方,选择GenericEventExecutorChooser,executors[Math.abs(idx.getAndIncrement() % executors.length)]。

五、Channel注册

Channel注册入口

选择EventLoop 本文为NioEventLoop

绑定Channel到EventExecutor 通过DefaultChannelPromise绑定Channel到EventExecutor(NioEventLoop)

将Channel注册到Selector

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 瓜农老梁 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • NioEventLoop类图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档