netty源碼基礎知識

1:
NioEventLoop:NIO 事件的循環  selector 的打開和事件
Selector類的select()方法會無限阻塞等待,直到有信道準備好了IO操做,或另外一個線程喚醒了它(調用了該選擇器的wakeup())。
selectNow()方法執行就緒檢查過程,但不阻塞。若是當前沒有通道就緒,它將當即返回0

2:
NioServerSocketChannel->AbstractNioMessageChannel
NioSocketChannel->AbstractNioByteChannel: AbstractUnsafe:bind->NioServerSocketChannel:dobind

監聽分發事件:NioEventLoop:processSelectedKey-->>NioMessageUnsafe:read
-->>NioServerSocketChannel:doReadMessages(批量《list》接受客戶端的請求,創建一個新NioSocketChannel)
--->>DefaultChannelPipeline:fireChannelRead-->
-->> AbstractChannelHandlerContext:channelRead--->>ServerBootstrap:ServerBootstrapAcceptor:channelRead
--->>NioEventLoop:register
3:循環監聽
SingleThreadEventExecutor() 新建時候會調用run(),而且賦值給本身的thread;run內部會循環selector
具體這個run何時啓動呢?
AbstractBootstrap:initAndRegister:  (ChannelFuture regFuture = group().register(channel);)
-->AbstractChannel:register( eventLoop.execute(new Runnable() )

4:LineBasedFrameDecoder
netty 中 LineBasedFrameDecoder 會調用slice(),切割bytebuf,可是底層只有一個bytebuf,其中一個修改,都會影響整個bytebuf

6.初始化 NioEventLoop 打開 selector

7.ChannelOutboundBuffer 存儲寫的信息,flush纔是真正的發送
  在寫如數據先判斷:isWritable(),是否能夠寫,實際會調用ChannelOutboundBuffer的方法判斷

8.ctx.writeAndFlush(message) 會將messge的buf進行裝換,假如不是isDirect,會裝換成Direct,而且是否老的buf

9. 寫入數據的時候假如是netty本身的線程,則直接發送。用戶的線程則走任務的形勢發送。防止多個線程引發的鎖的問題
10.在netty內部運行一個任務,netty會判斷是不是本身內部已經啓動的線程(  if (!inEventLoop()) ),是就運行,不然就放入一個隊列中(taskQueue)
,
相關文章
相關標籤/搜索