Netty源码剖析

Thread -> NioEventLoop, Netty的发送机,主要包含两种线程,一种处理连接,一种发送接收数据。

while(true) -> run()

Socket -> Channel

IOBytes -> ByteBuf

// 就是一个供读写的数据链
Logic Chain -> Pipeline

Logic -> ChannelHandler


Question:

1、socket在哪里创建

Netty服务端启动

1、创建服务端Channel

bind -> initAndRegister -> newChannel

channelFactory.newChannel()通过反射创建Channel

1、newSocket通过JDK创建底层channel
2、NioServerScoektSocketChannelCOnfig(TCP参数配置)
3、AbstractNioChannel.configureBlocking(false)

channelFactory 的clazz是在bootStrap的.channel(Class)传入的

2、初始化服务端Channel

init

1、init()
2、setchannelOptions, ChannelAttrs
3、setChildOptions、ChildAttrs
4、config Handler
5、add ServerBootstrapAcceptor(一个特殊的Handler)

3、注册Selector

1、AbstractChannel.register(channel)

channelAdded
channelRegistered

4、端口绑定

1、AbstractUnsafe.bind()

服务端启动核心路径总结

newChannel() -> init() -> register() -> doBind()

NioEventLoop

三个问题:

  • 默认Netty服务端起多少个线程?何时启动
  • Netty是如何解决jdk空轮询bug的
  • Netty如何保

NioEventLoop的创建

new NioEventLoopGroup()

NioEventLoop的启动

NioEventLoop的执行逻辑