Netty 源码(二)NioEventLoop 之 Channel 注册
Netty 源码(二)NioEventLoop 之 Channel 注册
Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html)
相关文章:

1. Channel 注册到 NioEventLoop
chnnel 初始化完成后就需要将其注册到对应的 NioEventLoop 上。
(1) NioEventLoopGroup 注册
// NioEventLoopGroup -> MultithreadEventLoopGroup
public ChannelFuture register(Channel channel) {
return next().register(channel);
}
group() 返回的是上文配置的 childGroup 对象,即 NioEventLoopGroup,每个 NioEventLoopGroup 持有多个 NioEventLoop,next 依次返回一个 NioEventLoop。
(2) NioEventLoop 注册
// NioEventLoop -> SingleThreadEventLoop
public ChannelFuture register(Channel channel) {
return register(new DefaultChannelPromise(channel, this));
}
public ChannelFuture register(final ChannelPromise promise) {
ObjectUtil.checkNotNull(promise, "promise");
promise.channel().unsafe().register(this, promise);
return promise;
}
可以看到最终调用对应 channel 的 unsafe 进行注册,下面看一下 unsafe 是如何注册的。
(3) Unsafe 注册
NioServerSocketChannel 的 unsafe = new NioMessageUnsafe(),而 NioMessageUnsafe 继承自 AbstractUnsafe。
// NioServerSocketChannel -> AbstractChannel.AbstractUnsafe
public final void register(EventLoop eventLoop, final ChannelPromise promise) {
// 省略...
AbstractChannel.this.eventLoop = eventLoop;
// 同一个 channel 的注册、读、写等都在 eventLoop 完成,避免多线程的锁竞争
if (eventLoop.inEventLoop()) {
// 将 channel 注册到 eventLoop 上
register0(promise);
} else {
try {
eventLoop.execute(new Runnable() {
@Override
public void run() {
register0(promise);
}
});
} catch (Throwable t) {
// 省略...
}
}
}
private void register0(ChannelPromise promise) {
// 1. 确保 channel 的状态是 open,最终调用 ch.isOpen()
if (!promise.setUncancellable() || !ensureOpen(promise)) {
return;
}
boolean firstRegistration = neverRegistered;
// 2. channel 注册到 eventLoop 上
doRegister();
neverRegistered = false;
registered = true;
// 3. 此时 channel 已经注册到 eventLoop 上,此时需要将注册的 handler 绑定到 channel 上。eg: ChannelInitializer
pipeline.invokeHandlerAddedIfNeeded();
safeSetSuccess(promise);
pipeline.fireChannelRegistered();
// 4. channel 状态为 active 就需要触发 ChannelActive 事件或准备读
if (isActive()) {
if (firstRegistration) {
pipeline.fireChannelActive();
} else if (config().isAutoRead()) {
beginRead();
}
}
}
register 中最重要的方法是调用 doRegister 进行注册,该方法调用了 JDK 底层的代码进行注册。
(4) doRegister
// AbstractNioChannel
protected void doRegister() throws Exception {
boolean selected = false;
for (;;) {
try {
// 1. 调用 JDK NIO 将 channel 注册到 eventLoop 的 selector 上
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
return;
} catch (CancelledKeyException e) {
if (!selected) {
// 2. 调用 selectNow 将注册的 channel 移除,不然有可能被缓存没有删除
// 移除后继续注册
eventLoop().selectNow();
selected = true;
} else {
// 3. JDK 提供的文档此时不会出现该异常,实际... JDK bug
throw e;
}
}
}
}
2. 注册感兴趣的事件
AbstractNioChannel#javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
register 方法注册 Java 原生 NIO 的 Channel 对象到 Selector 对象。但是为什么感兴趣事件的是 0 呢?正常情况下,对于服务端来说,需要注册 SelectionKey.OP_ACCEPT 事件。
(1) 注册方式是多态的,它即可以被 NIOServerSocketChannel 用来监听客户端的连接接入,也可以注册 SocketChannel 用来监听冉莹颖读或者写操作。
(2) 通过 SelectionKey#interestOps(int ops) 方法可以方便地修改监听操作位。所以,此处注册需要获取 SelectionKey 并给 AbstractNIOChannel 的成员变量 selectionKey 赋值。
- SelectionKey.OP_READ(1)
- SelectionKey.OP_WRITE(4)
- SelectionKey.OP_CONNECT(8)
- SelectionKey.OP_ACCEPT(16)
// AbstractChannel.AbstractUnsafe
public final void beginRead() {
assertEventLoop();
if (!isActive()) {
return;
}
try {
doBeginRead();
} catch (final Exception e) {
invokeLater(new Runnable() {
@Override
public void run() {
pipeline.fireExceptionCaught(e);
}
});
close(voidPromise());
}
}
// AbstractNioChannel
protected void doBeginRead() throws Exception {
// Channel.read() or ChannelHandlerContext.read() was called
final SelectionKey selectionKey = this.selectionKey;
if (!selectionKey.isValid()) {
return;
}
readPending = true;
// 重新注册感兴趣的事件类型,readInterestOp 是 channel 初始化的时候传进来的
final int interestOps = selectionKey.interestOps();
if ((interestOps & readInterestOp) == 0) {
selectionKey.interestOps(interestOps | readInterestOp);
}
}
到此 NioServerSocketChannel 就重新注册上了 OP_ACCEPT 事件
每天用心记录一点点。内容也许不重要,但习惯很重要!
Netty 源码(二)NioEventLoop 之 Channel 注册的更多相关文章
- Netty源码—二、server启动(2)
我们在使用Netty的时候的初始化代码一般如下 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGro ...
- Netty源码—一、server启动(1)
Netty作为一个Java生态中的网络组件有着举足轻重的位置,各种开源中间件都使用Netty进行网络通信,比如Dubbo.RocketMQ.可以说Netty是对Java NIO的封装,比如ByteBu ...
- Netty 源码 Channel(二)核心类
Netty 源码 Channel(二)核心类 Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) 一.Channel 类图 二. ...
- Netty 源码 Channel(二)主要类
Netty 源码 Channel(二)主要类 Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) 一.Channel 类图 二. ...
- Netty 源码解析(二):Netty 的 Channel
本文首发于微信公众号[猿灯塔],转载引用请说明出处 接下来的时间灯塔君持续更新Netty系列一共九篇 Netty源码解析(一):开始 当前:Netty 源码解析(二): Netty 的 Channel ...
- Netty 源码 NioEventLoop(三)执行流程
Netty 源码 NioEventLoop(三)执行流程 Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) 上文提到在启动 N ...
- Netty 源码 NioEventLoop(一)初始化
Netty 源码 NioEventLoop(一)初始化 Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) Netty 基于事件 ...
- Netty源码分析之NioEventLoop(三)—NioEventLoop的执行
前面两篇文章Netty源码分析之NioEventLoop(一)—NioEventLoop的创建与Netty源码分析之NioEventLoop(二)—NioEventLoop的启动中我们对NioEven ...
- Netty 源码解析(八): 回到 Channel 的 register 操作
原创申明:本文由公众号[猿灯塔]原创,转载请说明出处标注 今天是猿灯塔“365篇原创计划”第八篇. 接下来的时间灯塔君持续更新Netty系列一共九篇 Netty 源码解析(一): 开始 Netty 源 ...
随机推荐
- jstl-随机数-借用jsp嵌入的代码
) %></c:set> ${rand }
- java和c#中String
java中: c#中: 1.拼接字符串 sql语句中 in() str="'001','002','003'";至于产生string就这样 str1="'001'&qu ...
- sql数据库之多库查询
连接到数据库服务器gwsps07上,打开查询分析器,如何获取gwrenshi数据库中的数据? 查询语句如下: select * from GWRENSHI.CGC.dbo.PERempms(serve ...
- Neumann's Principle and Curie laws
Neumann's Principle Neumann's principle, or principle of symmetry, states that, if a crystal is inva ...
- matlab画图标题自定义字体大小
title('标题','fontname','Times New Roman','Color','b','FontSize',20);字体是Times New Roman,颜色是蓝色('b'即blue ...
- c++面向行的输入getline()和get()
来源:c++ primer plus 在c++里当我们输入一个字符串时习惯用cin,但是cin只能读取一段不含空格的字符串,如果我们需要读取一段包含空格的字符串时,就需要用到getline()或get ...
- Android模拟器故障:waiting for target deviceto come online
关闭再打开模拟器.删除再新建模拟器均无效. 解决办法:在AVD Manager中,选择立即冷启动(Cold Boot Now)模拟器.
- Django具体操作(五)
一.中间件的概念 中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级,并且在全局上改变django的输入与输出.因为改变的是全局,所以需要谨慎实用,用不好会影 ...
- Exceptions
[定义] error: external, like out of memory exception: internal, like file not found 父类都是throwable 逻辑有错 ...
- lendinghome oa 准备
hardcode版本 估计只能过一个吧 import java.util.*; public class NextServer { Map<Integer, Integer> server ...