深入理解 Netty 中的 Channel 创建机制
前言
如果你刚接触 Netty,可能会好奇:Netty 的 Channel 和 JDK 原生的 Channel 是什么关系?它们是怎么关联起来的?
这篇文章将带你一步步揭开这个谜团。简单来说:
- NioSocketChannel(Netty 客户端)封装了 JDK 的 SocketChannel
- NioServerSocketChannel(Netty 服务端)封装了 JDK 的 ServerSocketChannel
- 它们是一对一的关系,Netty 的 Channel 是对 JDK Channel 的增强封装

一、从启动代码说起
无论是客户端的 Bootstrap 还是服务端的 ServerBootstrap,在启动时都会调用 channel() 方法来指定使用哪种 Channel。
1.1 客户端启动代码示例
private void connect(String inetHost, int inetPort) {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class); // 👈 关键:指定使用 NioSocketChannel
b.option(ChannelOption.AUTO_READ, true);
b.handler(new MyChannelInitializer());
ChannelFuture f = b.connect(inetHost, inetPort).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
}
}
1.2 服务端启动代码示例
private void bind(int port) {
ServerBootstrap b = new ServerBootstrap();
b.group(parentGroup, childGroup) // 配置主从 Reactor 线程模型
.channel(NioServerSocketChannel.class) // 👈 关键:指定使用 NioServerSocketChannel
.option(ChannelOption.SO_BACKLOG, 128) // 设置 TCP 连接队列大小
.childHandler(new MyChannelInitializer()); // 设置子通道处理器
}
你可能会问:为什么只是传了一个 Class 对象,Netty 就能创建出 Channel 实例呢?
答案就在 channel() 方法的实现里。
二、channel() 方法做了什么?
让我们深入源码看看 channel() 方法的实现逻辑:
public B channel(Class<? extends C> channelClass) {
if (channelClass == null) {
throw new NullPointerException("channelClass");
} else {
// 👇 核心:创建一个 ReflectiveChannelFactory 工厂
return (B)this.channelFactory(new ReflectiveChannelFactory(channelClass));
}
}
public B channelFactory(io.netty.channel.ChannelFactory<? extends C> channelFactory) {
return (B)this.channelFactory(channelFactory);
}
@Deprecated
public B channelFactory(ChannelFactory<? extends C> channelFactory) {
if (channelFactory == null) {
throw new NullPointerException("channelFactory");
} else if (this.channelFactory != null) {
throw new IllegalStateException("channelFactory set already");
} else {
// 👇 保存 channelFactory,后续创建 Channel 时会用到
this.channelFactory = channelFactory;
return (B)this.self();
}
}
核心逻辑:
- 接收一个 Channel 的 Class 对象(如
NioSocketChannel.class) - 创建一个
ReflectiveChannelFactory工厂实例 - 将这个工厂保存到
channelFactory字段中
那么,ReflectiveChannelFactory 又是什么呢?
三、ReflectiveChannelFactory:反射工厂的秘密
ReflectiveChannelFactory 是一个使用反射来创建 Channel 实例的工厂类:
public class ReflectiveChannelFactory<T extends Channel> implements ChannelFactory<T> {
// 保存 Channel 类的无参构造器
private final Constructor<? extends T> constructor;
public ReflectiveChannelFactory(Class<? extends T> clazz) {
ObjectUtil.checkNotNull(clazz, "clazz");
try {
// 👇 获取无参构造器(这就是为什么 Channel 类必须有无参构造方法)
this.constructor = clazz.getConstructor();
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + StringUtil.simpleClassName(clazz) +
" does not have a public non-arg constructor", e);
}
}
@Override
public T newChannel() {
try {
// 👇 通过反射调用无参构造器创建实例
return constructor.newInstance();
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
}
}
}
工作原理:
- 构造方法中获取传入 Channel 类的无参构造器(如
NioSocketChannel的无参构造器) - 保存这个构造器引用
- 当需要创建 Channel 时,调用
newChannel()方法通过反射实例化
现在你明白了:Netty 使用反射机制来创建 Channel 实例。
那么,这个 newChannel() 方法什么时候被调用呢?答案是在 connect() 或 bind() 方法中。
四、Channel 创建的完整流程(以客户端为例)
让我们跟踪客户端调用 connect() 方法后,NioSocketChannel 是如何被创建并关联到 JDK 的 SocketChannel 的:
4.1 connect() 方法调用链
// 第一步:用户调用 connect
public ChannelFuture connect(String inetHost, int inetPort) {
return this.connect(InetSocketAddress.createUnresolved(inetHost, inetPort));
}
// 第二步:重载方法
public ChannelFuture connect(SocketAddress remoteAddress) {
if (remoteAddress == null) {
throw new NullPointerException("remoteAddress");
} else {
this.validate(); // 校验参数是否正确设置
// 👇 核心方法
return this.doResolveAndConnect(remoteAddress, this.config.localAddress());
}
}
4.2 doResolveAndConnect() 方法
private ChannelFuture doResolveAndConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) {
// 👇 关键:初始化并注册 Channel
ChannelFuture regFuture = this.initAndRegister();
final Channel channel = regFuture.channel();
// ... 省略后续代码
}
4.3 initAndRegister() 方法:真正创建 Channel 的地方
final ChannelFuture initAndRegister() {
Channel channel = null;
try {
// 👇 这里!通过 channelFactory 创建 Channel 实例
channel = this.channelFactory.newChannel();
this.init(channel);
} catch (Throwable t) {
// ... 异常处理
}
return regFuture;
}
这里的 this.channelFactory 就是前面 channel() 方法设置的 ReflectiveChannelFactory 实例。
调用 newChannel() 方法:
public T newChannel() {
try {
// 👇 通过反射调用 NioSocketChannel 的无参构造器
return (T)(this.constructor.newInstance());
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + this.constructor.getDeclaringClass(), t);
}
}
调用链总结:
connect()
→ doResolveAndConnect()
→ initAndRegister()
→ channelFactory.newChannel() // ReflectiveChannelFactory
→ constructor.newInstance() // 反射调用 NioSocketChannel 无参构造器
→ NioSocketChannel() // 开始执行构造方法
五、NioSocketChannel 构造过程:关联 JDK 的 SocketChannel
现在进入 NioSocketChannel 的构造方法,看看它是如何创建并关联 JDK 的 SocketChannel 的:
5.1 NioSocketChannel 无参构造器
private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();
public NioSocketChannel() {
// 👇 调用重载构造器,传入 SelectorProvider
this(DEFAULT_SELECTOR_PROVIDER);
}
SelectorProvider 是 JDK NIO 提供的工具类,用于创建 Selector、ServerSocketChannel、SocketChannel 等。
5.2 带 SelectorProvider 参数的构造器
public NioSocketChannel(SelectorProvider provider) {
// 👇 关键:newSocket(provider) 创建 JDK 的 SocketChannel
this(newSocket(provider));
}
5.3 newSocket() 方法:创建 JDK 的 SocketChannel
private static java.nio.channels.SocketChannel newSocket(SelectorProvider provider) {
try {
// 👇 这里!创建 JDK NIO 的 SocketChannel 实例
return provider.openSocketChannel();
} catch (IOException e) {
throw new ChannelException("Failed to open a socket.", e);
}
}
重点来了: 在这一步,Netty 的 NioSocketChannel 创建了 JDK 底层的 java.nio.channels.SocketChannel 实例。
5.4 带 SocketChannel 参数的构造器
public NioSocketChannel(Channel parent, java.nio.channels.SocketChannel socket) {
super(parent, socket); // 👈 调用父类构造器
this.config = new NioSocketChannelConfig(this, socket.socket()); // 创建配置对象
}
这里做了两件事:
- 调用父类构造器,传入 JDK 的 SocketChannel
- 创建
NioSocketChannelConfig配置对象(保存 Channel 的各种配置信息)
六、父类构造器:设置非阻塞模式和感兴趣的事件
继续看父类构造器做了什么:
6.1 AbstractNioByteChannel 构造器
protected AbstractNioByteChannel(Channel parent, SelectableChannel ch) {
// 👇 传入参数 1 代表 SelectionKey.OP_READ
// 客户端关心的是 OP_READ 事件,等待读取服务端返回的数据
super(parent, ch, 1);
}
这里的 1 对应 SelectionKey.OP_READ,表示客户端 Channel 关心读事件。
6.2 AbstractNioChannel 构造器:核心配置
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch; // 👈 保存 JDK 的 SocketChannel 引用
// 👇 保存感兴趣的事件类型(OP_READ),后续注册到 Selector 时会用到
this.readInterestOp = readInterestOp;
try {
// 👇 关键:设置 Channel 为非阻塞模式
ch.configureBlocking(false);
} catch (IOException e) {
// ... 异常处理
}
}
这里做了三件重要的事:
- 保存 JDK 的 SocketChannel 引用到
this.ch字段 - 保存感兴趣的事件类型(
SelectionKey.OP_READ)到this.readInterestOp字段 - 将 JDK 的 SocketChannel 设置为非阻塞模式
6.3 服务端的构造过程类似
NioServerSocketChannel 的构造方法也是类似的流程:
public NioServerSocketChannel(java.nio.channels.ServerSocketChannel channel) {
// 👇 传入参数 16 代表 SelectionKey.OP_ACCEPT
// 服务端关心的是 OP_ACCEPT 事件,等待客户端连接
super((Channel)null, channel, 16);
this.config = new NioServerSocketChannelConfig(this, this.javaChannel().socket());
}
服务端关心的是 SelectionKey.OP_ACCEPT 事件(值为 16),用于接受客户端连接。
七、SelectionKey 事件类型说明
public static final int OP_READ = 1 << 0; // 1 - 读操作(客户端和服务端都会用)
public static final int OP_WRITE = 1 << 2; // 4 - 写操作
public static final int OP_CONNECT = 1 << 3; // 8 - 连接操作(客户端连接服务端时用)
public static final int OP_ACCEPT = 1 << 4; // 16 - 接受连接操作(服务端接受客户端连接时用)
- 客户端 NioSocketChannel:关心
OP_READ事件(值为 1),等待读取服务端返回的数据 - 服务端 NioServerSocketChannel:关心
OP_ACCEPT事件(值为 16),等待接受客户端连接
八、完整流程图
完整流程:
1. Bootstrap.channel(NioSocketChannel.class)
↓
2. 创建 ReflectiveChannelFactory,保存 NioSocketChannel 的无参构造器
↓
3. Bootstrap.connect() 调用
↓
4. channelFactory.newChannel() 通过反射创建 NioSocketChannel 实例
↓
5. NioSocketChannel 构造器执行
↓
6. 调用 SelectorProvider.openSocketChannel() 创建 JDK 的 SocketChannel
↓
7. 将 JDK 的 SocketChannel 设置为非阻塞模式
↓
8. 保存感兴趣的事件类型(OP_READ)
↓
9. NioSocketChannel 创建完成,内部持有 JDK 的 SocketChannel 引用
九、总结
通过这篇文章,我们深入分析了 Netty Channel 的创建机制,核心要点如下:
-
工厂模式:Netty 使用
ReflectiveChannelFactory通过反射创建 Channel 实例 -
封装关系:
NioSocketChannel封装了 JDK 的SocketChannelNioServerSocketChannel封装了 JDK 的ServerSocketChannel- 它们是一对一的关系
-
创建时机:
- 客户端:在
connect()方法中创建 - 服务端:在
bind()方法中创建
- 客户端:在
-
初始化配置:
- 设置为非阻塞模式
- 保存感兴趣的事件类型(客户端 OP_READ,服务端 OP_ACCEPT)
-
设计优势:
- 通过工厂模式解耦 Channel 的创建
- 通过封装增强 JDK 原生 Channel 的功能
- 统一的 API 设计,简化使用
:
NioSocketChannel封装了 JDK 的SocketChannelNioServerSocketChannel封装了 JDK 的ServerSocketChannel- 它们是一对一的关系
-
创建时机:
- 客户端:在
connect()方法中创建 - 服务端:在
bind()方法中创建
- 客户端:在
-
初始化配置:
- 设置为非阻塞模式
- 保存感兴趣的事件类型(客户端 OP_READ,服务端 OP_ACCEPT)
-
设计优势:
- 通过工厂模式解耦 Channel 的创建
- 通过封装增强 JDK 原生 Channel 的功能
- 统一的 API 设计,简化使用
1108



被折叠的 条评论
为什么被折叠?



