本专栏基于4.1.73.Final版本进行解析,源码地址为:https://github.com/lhj502819/netty/tree/v502819-main
系列文章
- 你知道都有哪些I/O模型吗?
- Java NIO三大角色Channel、Buffer、Selector
- Doug lea《Scalable IO in Java》翻译
- Reactor模型你知道都有哪些吗?
- Netty服务端创建源码流程解析
- EventLoopGroup到底是个啥?
- 未完待续…
创作不易,如果对您有帮助,麻烦辛苦下小手点个关注,有任何问题都可以私信交流哈。
祝您虎年虎虎生威。
相信大家对创建一个Netty服务端已经很熟悉了,下边是一个简单的服务端的例子:
public final class EchoServer {
static final boolean SSL = System.getProperty("ssl") != null;
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
// Configure the server.
//创建两个EventLoopGroup对象
EventLoopGroup bossGroup = new NioEventLoopGroup(1);//创建boos线程组,用于服务端接受客户端的连接
EventLoopGroup workerGroup = new NioEventLoopGroup();//创建worker线程组,用于进行SocketChannel的数据读写,处理业务逻辑
//创建Handler
final EchoServerHandler serverHandler = new EchoServerHandler();
try {
//创建ServerBootstrap对象
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)//设置EventLoopGroup
.channel(NioServerSocketChannel.class)//设置要被实例化的NioServerSocketChannel类
.option(ChannelOption.SO_BACKLOG, 100) //设置NioServerSocketChannel的可设置项
.handler(new LoggingHandler(LogLevel.INFO))//设置NioServerSocketChannel的处理器
.childHandler(new ChannelInitializer<SocketChannel>() {//设置处理连入的Client的SocketChannel的处理器
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
//p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(serverHandler);
}
});
// Start the server.
//绑定端口,并同步等待成功,即启动服务端
ChannelFuture f = b.bind(PORT).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("测试Channel绑定成功后回调");
}
}).sync();
// Wait until the server socket is closed.
//监听服务端关闭,并阻塞等待
//这里并不是关闭服务器,而是“监听”服务端关闭
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
//优雅关闭两个EventLoopGroup对象
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
从上边的例子中我们可以看到有这么几个伙计,ServerBootstrap
、NioServerSocketChannel
、EventLoop
、NioEventLoop
、ChannelHandler
、ChannelPipeline
,今天我们主要聊的是ServerBootstrap
以及它与其它类之间的关系。
时序图
整个服务端创建的时序图如下:
在下图中我们可以看到以Bootstrap结尾的三个类的类图,ServerBootstrap
和Bootstrap
分别为服务端的启动类和客户端的启动类,这两个类继承自AbstractBootstrap
,大部分的方法和职责都是相同的,因此我们主要讲解AbstractBootstrap
。
AbstractBootstrap主要方法
//B继承自AbstractBootstrap,用于表示自身的类型
//C继承自Channel类,表示创建的Channel类型
public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C extends Channel> implements Cloneable {
................省略部分代码...................
/**
* EventLoopGroup对象
*/
volatile EventLoopGroup group;
/**
* Channel工厂,用于创建Channel对象
*/
@SuppressWarnings("deprecation")
private volatile ChannelFactory<? extends C> channelFactory;
/**
* 本地地址
*/
private volatile SocketAddress localAddress;
// The order in which ChannelOptions are applied is important they may depend on each other for validation
// purposes.
/**
* 可选项集合
*/
private final Map<ChannelOption<?>, Object> options = new LinkedHashMap<ChannelOption<?>, Object>();
/**
* 属性集合,可以理解成java.nio.channels.SelectionKey的attachment属性,并且类型为Map
*/
private final Map<AttributeKey<?>, Object> attrs = new ConcurrentHashMap<AttributeKey<?>, Object>();
/**
* 处理器
*/
private volatile ChannelHandler handler;
AbstractBootstrap() {
// Disallow extending from a different package.
}
AbstractBootstrap(AbstractBootstrap<B, C> bootstrap) {
group = bootstrap.group;
channelFactory = bootstrap.channelFactory;
handler = bootstrap.handler;
localAddress = bootstrap.localAddress;
/**
* 这里为何设置options时要加锁?因为options可能再另外的线程被修改,例如option方法{@link #option(ChannelOption, Object)}
*/
synchronized (bootstrap.options) {
options.putAll(bootstrap.options);
}
attrs.putAll(bootstrap.attrs);
}
................省略部分代码...................
}
group()
//用于设置EventLoopGroup,由子类ServerBootstrap调用,这些EventLoopGroup}用于处理ServerChannel和Channel的所有事件和 IO。
public B group(EventLoopGroup group) {
ObjectUtil.checkNotNull(group, "group");
if (this.group != null) {
throw new IllegalStateException("group set already");
}
this.group = group;
return self();
}
channel(Class)
public B channel(Class<? extends C> channelClass) {
return channelFactory(new ReflectiveChannelFactory<C>(
ObjectUtil.checkNotNull(channelClass, "channelClass")
));
}
设置要被实例化的Channel类,底层是通过工厂类进行了封装
ChannelFactory
用于创建Channel的工厂类,ReflectiveChannelFactory
底层利用反射创建Channel,代码如下。
public class ReflectiveChannelFactory<T extends Channel> implements ChannelFactory<T> {
/**
* 需要在初始化时就获取到对应Channel的默认构造器,为创建Channel实例时减少开销
*/
private final Constructor<? extends T> constructor;
public ReflectiveChannelFactory(Class<? extends T> clazz) {
ObjectUtil.checkNotNull(clazz, "clazz");
try {
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 {
//Channel的无参构造函数
return constructor.newInstance();
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
}
}
}
option(ChannelOption option, T value)
用于设置Channel的可选项,底层使用Map存储。
public <T> B option(ChannelOption<T> option, T value) {
ObjectUtil.checkNotNull(option, "option");
synchronized (options) {
if (value == null) {
options.remove(option);
} else {
options.put(option, value);
}
}
return self();
}
attr(AttributeKey key, T value)
用于设置Channel的属性,就像SelectionKey的attachment。
public <T> B attr(AttributeKey<T> key, T value) {
ObjectUtil.checkNotNull(key, "key");
if (value == null) {
attrs.remove(key);
} else {
attrs.put(key, value);
}
return self();
}
handler(ChannelHandler handler)
设置Channel的处理器
public B handler(ChannelHandler handler) {
this.handler = ObjectUtil.checkNotNull(handler, "handler");
return self();
}
validate
校验配置是否正确,{@link #bind()}
方法会调用此方法
/**
* Validate all the parameters. Sub-classes may override this, but should
* call the super method in that case.
*
*
*/
public B validate() {
if (group == null) {
throw new IllegalStateException("group not set");
}
if (channelFactory == null) {
throw new IllegalStateException("channel or channelFactory not set");
}
return self();
}
clone
抽象方法,具体实现在子类,子类都是深拷贝一个AbstractBootstrap实例,但并不是所有的属性都是深拷贝,具体可以看构造方法,只有options和attrs才深拷贝,其他的都是浅拷贝。
public abstract B clone();
config
获取配置类AbstractBootstrapConfig
,对应子类就是ServerBootstrapConfig
和BootstrapConfig
,ServerBootstrapConfig就是集成了ServerBootstrap,代码如下:
//ServerBootstrap 类,可以看到ServerBootstrapConfig将ServerBootstrap组合为自己的属性了
private final ServerBootstrapConfig config = new ServerBootstrapConfig(this);
setChannelOptions
设置传入的Channel的多个可选项,代码如下,不过还有一个option方法,这两个方法的区别是,此方法要设置的是已经创建的Channel的可选项,而option方法是要设置未创建的Channel的可选项。
static void setChannelOptions(
Channel channel, Map.Entry<ChannelOption<?>, Object>[] options, InternalLogger logger) {
for (Map.Entry<ChannelOption<?>, Object> e: options) {
setChannelOption(channel, e.getKey(), e.getValue(), logger);
}
}
private static void setChannelOption(
Channel channel, ChannelOption<?> option, Object value, InternalLogger logger) {
try {
if (!channel.config().setOption((ChannelOption<Object>) option, value)) {
logger.warn("Unknown channel option '{}' for channel '{}'", option, channel);
}
} catch (Throwable t) {
logger.warn(
"Failed to set channel option '{}' with value '{}' for channel '{}'", option, value, channel, t);
}
}
绑定端口、启动服务端的流程
整个流程中,AbstractBootstrap和ServerBootstrap都会有涉猎,因为部分是异步执行的,代码的跳跃性较大,请大家仔细看,如果有不明白的自己调试下就清楚了
bind
AbstractBootstrap
此方法主要用于绑定端口,启动服务端
//绑定端口,并同步等待成功,即启动服务端
ChannelFuture f = b.bind(PORT).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("测试Channel绑定成功后回调");
}
}).sync();
public ChannelFuture bind(int inetPort) {
return bind(new InetSocketAddress(inetPort));
}
public ChannelFuture bind(SocketAddress localAddress) {
//校验服务启动
validate();
//绑定本地地址
return doBind(ObjectUtil.checkNotNull(localAddress, "localAddress"));
}
public ChannelFuture bind() {
validate();
SocketAddress localAddress = this.localAddress;
if (localAddress == null) {
throw new IllegalStateException("localAddress not set");
}
return doBind(localAddress);
}
public ChannelFuture bind(String inetHost, int inetPort) {
return bind(SocketUtils.socketAddress(inetHost, inetPort));
}
public ChannelFuture bind(InetAddress inetHost, int inetPort) {
return bind(new InetSocketAddress(inetHost, inetPort));
}
此方法的返回类型为ChannelFuture
,我们知道Java也有一个Future是用于异步回调的,Netty的ChannelFuture
也是一样,异步的绑定端口,如果需要同步,则需要调用ChannelFuture#sync
方法。
doBind
private ChannelFuture doBind(final SocketAddress localAddress) {
//初始化并注册一个Channel对象,因为注册是异步的过程,所以返回一个ChannelFuture
//initAndRegister我们在下边进行对应解析
final ChannelFuture regFuture = initAndRegister();
final Channel channel = regFuture.channel();
if (regFuture.cause() != null) {
//如果发生异常,直接返回
return regFuture;
}
//这里又由于注册是异步的,因此需要判断是否注册成功了,分别进行不同的处理
if (regFuture.isDone()) {//如果注册完成了,调用doBind0方法,绑定Channel的端口,并注册Channel到SelectionKey中。
//绑定Channel的端口,并注册Channel到SelectionKey中
// At this point we know that the registration was complete and successful.
ChannelPromise promise = channel.newPromise();
doBind0(regFuture, channel, localAddress, promise);
return promise;
} else {//如果未注册完成,则调用ChannelFuture#addListener添加监听器,监听注册完成事件,进行对应处理
// Registration future is almost always fulfilled already, but just in case it's not.
final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
regFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Throwable cause = future.cause();
if (cause != null) {
// Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
// IllegalStateException once we try to access the EventLoop of the Channel.
promise.setFailure(cause);
} else {
// Registration was successful, so set the correct executor to use.
// See https://github.com/netty/netty/issues/2586
promise.registered();
doBind0(regFuture, channel, localAddress, promise);
}
}
});
return promise;
}
}
initAndRegister
/**
* 初始化并注册一个Channel对象,返回一个ChannelFuture对象
* @return
*/
final ChannelFuture initAndRegister() {
Channel channel = null;
try {
//创建Channel对象,这个ChannelFactory是在调用#channel方法设置的,#channel方法是用来设置实例化的NioServerSocketChannel类,而不是真正的实例化
channel = channelFactory.newChannel();
//初始化Channel配置,抽象方法,需要ServerBootstrap和BootStrap进行实现
init(channel);
} catch (Throwable t) {
//异常
if (channel != null) {//如果已创建channel则关闭channel
// channel can be null if newChannel crashed (eg SocketException("too many open files"))
channel.unsafe().closeForcibly();
// as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
}
//返回带异常的DefaultChannelPromise对象,同时需要绑定一个FailedChannel
// as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t);
}
//注册Channel到EventLoopGroup中,在方法内部EventLoopGroup会分配一个EventLoop对象给Channel,将Channel注册到其上
ChannelFuture regFuture = config().group().register(channel);
if (regFuture.cause() != null) {
//如果发生异常,并且Channel已经注册成功,则调用#close方法关闭Channel,会触发Channel关闭事件
if (channel.isRegistered()) {
channel.close();
} else {
//如果发生异常并且没有注册成功,则调用closeForcibly强制关闭,该方法不会触发关闭事件,因为还没有注册成功,因此不用触发其他事件
channel.unsafe().closeForcibly();//强制关闭Channel
}
}
// If we are here and the promise is not failed, it's one of the following cases:
// 1) If we attempted registration from the event loop, the registration has been completed at this point.
// i.e. It's safe to attempt bind() or connect() now because the channel has been registered.
// 2) If we attempted registration from the other thread, the registration request has been successfully
// added to the event loop's task queue for later execution.
// i.e. It's safe to attempt bind() or connect() now:
// because bind() or connect() will be executed *after* the scheduled registration task is executed
// because register(), bind(), and connect() are all bound to the same thread.
return regFuture;
}
创建Channel对象
NioServerSocketChannel
我们这里以NioServerSocketChannel为例,NioServerSocketChannel的类图如下,后边会用到。
public class NioServerSocketChannel extends AbstractNioMessageChannel
implements io.netty.channel.socket.ServerSocketChannel {
private static ServerSocketChannel newSocket(SelectorProvider provider) {
try {
//和ServerSocketChannel#open一样
/**
* public static ServerSocketChannel open() throws IOException {
* return SelectorProvider.provider().openServerSocketChannel();
* }
*/
return provider.openServerSocketChannel();
} catch (IOException e) {
throw new ChannelException(
"Failed to open a server socket.", e);
}
}
/**
* Channel对应的配置对象,每种Channel实现类,也会对应一个ChannelConfig实现类,例如NioServerSocketChannel对应ServerSocketChannelConfig
*/
private final ServerSocketChannelConfig config;
/**
* Create a new instance
*/
public NioServerSocketChannel() {
this(newSocket(DEFAULT_SELECTOR_PROVIDER));
}
/**
* Create a new instance using the given {@link SelectorProvider}.
*/
public NioServerSocketChannel(SelectorProvider provider) {
this(newSocket(provider));
}
/**
* Create a new instance using the given {@link ServerSocketChannel}.
*/
public NioServerSocketChannel(ServerSocketChannel channel) {
//调用父类的构造方法,传入的SelectionKey为OP_ACCEPT,表示感兴趣的事件为OP_ACCEPT
super(null, channel, SelectionKey.OP_ACCEPT);
//初始化config属性
config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}
}
#newSocket
方法的返回类型为java.nio.channels.ServerSocketChannel
,说明Netty Channel的底层还是Java的SocketChannel- 在
41
行的构造方法中,调用了父类的构造方法,并传入了自己感兴趣的事件,这里就和Java的服务端NIO编程一样了
AbstractNioMessageChannel
//操作消息的基类
public abstract class AbstractNioMessageChannel extends AbstractNioChannel {
/**
* @see AbstractNioChannel#AbstractNioChannel(Channel, SelectableChannel, int)
*/
protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent, ch, readInterestOp);
}
@Override
protected void doBeginRead() throws Exception {
if (inputShutdown) {
return;
}
super.doBeginRead();
}
}
AbstractNioChannel
/**
* 主要是对Selector的封装操作
*/
public abstract class AbstractNioChannel extends AbstractChannel {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(AbstractNioChannel.class);
//Netty NIO Channel对象,持有的Java原生NIO的Channel对象
private final SelectableChannel ch;
//感兴趣的读事件的操作位值,AbstractNioMessageChannel是SelectionKey.OP_ACCEPT,AbstractNioByteChannel是SelectionKey.OP_READ
protected final int readInterestOp;
volatile SelectionKey selectionKey;
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch;
//设置感兴趣的事件
this.readInterestOp = readInterestOp;
try {
//设置为非阻塞
ch.configureBlocking(false);
} catch (IOException e) {
//如果发生异常则关闭NIO Channel
try {
ch.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
}
throw new ChannelException("Failed to enter non-blocking mode.", e);
}
}
}
AbstractChannel
public abstract class AbstractChannel extends DefaultAttributeMap implements Channel {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannel.class);
//父Channel,对于NioServerSocketChannel parent为空
private final Channel parent;
//Channel编号
private final ChannelId id;
private final Unsafe unsafe;
//默认的ChannelPipeline
private final DefaultChannelPipeline pipeline;
/**
* Creates a new instance.
*
* @param parent
* the parent of this channel. {@code null} if there's no parent.
*/
protected AbstractChannel(Channel parent) {
this.parent = parent;
//创建一个Channel ID
id = newId();
unsafe = newUnsafe();
pipeline = newChannelPipeline();
}
}
初始化Channel配置
由ServerBootstrap
和Bootstrap
自行实现,还是以ServerBootstrap
为例
void init(Channel channel) {
setChannelOptions(channel, newOptionsArray(), logger);
setAttributes(channel, newAttributesArray());
ChannelPipeline p = channel.pipeline();
//记录当前的属性
final EventLoopGroup currentChildGroup = childGroup;
final ChannelHandler currentChildHandler = childHandler;
final Entry<ChannelOption<?>, Object>[] currentChildOptions = newOptionsArray(childOptions);
final Entry<AttributeKey<?>, Object>[] currentChildAttrs = newAttributesArray(childAttrs);
//添加ChannelInitializer对象到pipeline中,用于后续初始化,ChannelHandler到pipeline中
//为什么使用ChannelInitializer进行初始化?而不是直接添加到pipeline中
//因为此时Channel还没有注册到EventLoop中,如果调用eventLoop().execute会抛出Exception in thread "main" java.lang.IllegalStateException: channel not registered to an event loop异常
p.addLast(new ChannelInitializer<Channel>() {
@Override
public void initChannel(final Channel ch) {
final ChannelPipeline pipeline = ch.pipeline();
//添加配置的ChannelHandler到pipeline中
ChannelHandler handler = config.handler();
if (handler != null) {
pipeline.addLast(handler);
}
//添加ServerBootstrapAcceptor到pipeline中
//eventLoop().execute(new Runnable()->{...})实际上只是向NioEventLoop的taskQueue添加了一个任务,并不会执行,而是由NioEventLoop去不断轮询执行的,后边还会有很多类似的操作,都是为了异步化
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
pipeline.addLast(new ServerBootstrapAcceptor(
ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
}
});
}
注册Channel到EventLoopGroup中
通过调用EventLoopGroup#register
方法进行注册,最终会执行到AbstractUnsafe#register
进行注册,AbstractUnsafe
是NioMessageUnsafe
的父类
public final void register(EventLoop eventLoop, final ChannelPromise promise) {
//判断EventLoop不为空
ObjectUtil.checkNotNull(eventLoop, "eventLoop");
if (isRegistered()) {
promise.setFailure(new IllegalStateException("registered to an event loop already"));
return;
}
//校验Channel和EventLoop是否匹配,因为它们都有很多实现类型
//要求为NioEventLoop
if (!isCompatible(eventLoop)) {
promise.setFailure(
new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
return;
}
//设置Channel的EventLoop属性
AbstractChannel.this.eventLoop = eventLoop;
//在EventLoop中执行注册逻辑
if (eventLoop.inEventLoop()) {
register0(promise);
} else {
try {
eventLoop.execute(new Runnable() {
@Override
public void run() {
register0(promise);
}
});
} catch (Throwable t) {
logger.warn(
"Force-closing a channel whose registration task was not accepted by an event loop: {}",
AbstractChannel.this, t);
//强制关闭Channel
closeForcibly();
//通知CloseFuture已经关闭
closeFuture.setClosed();
//回调通知promise发生该异常
safeSetFailure(promise, t);
}
}
}
register0
//AbstractChannel.java
/**
* 注册逻辑
*/
private void register0(ChannelPromise promise) {
try {
// check if the channel is still open as it could be closed in the mean time when the register
// call was outside of the eventLoop
if (!promise.setUncancellable() || !ensureOpen(promise)) {//确保Channel是打开的
return;
}
//用于记录是否为首次注册
boolean firstRegistration = neverRegistered;
//执行注册逻辑
doRegister();
//标记已经非首次注册
neverRegistered = false;
//标记Channel已经注册过了
registered = true;
// Ensure we call handlerAdded(...) before we actually notify the promise. This is needed as the
// user may already fire events through the pipeline in the ChannelFutureListener.
//触发ChannelInitializer执行,进行Handler初始化
pipeline.invokeHandlerAddedIfNeeded();
//回调promise执行成功,在doBind方法中regFuture注册的ChannelFutureListener
safeSetSuccess(promise);
//触发通知已注册事件
pipeline.fireChannelRegistered();
// Only fire a channelActive if the channel has never been registered. This prevents firing
// multiple channel actives if the channel is deregistered and re-registered.
if (isActive()) {
if (firstRegistration) {
pipeline.fireChannelActive();
} else if (config().isAutoRead()) {
// This channel was registered before and autoRead() is set. This means we need to begin read
// again so that we process inbound data.
//
// See https://github.com/netty/netty/issues/4805
beginRead();
}
}
} catch (Throwable t) {
// Close the channel directly to avoid FD leak.
//发生异常时和register()方法处理逻辑一样
closeForcibly();
closeFuture.setClosed();
safeSetFailure(promise, t);
}
}
doRegister,注册Selector
//AbstractNioChannel.java
/**
* 将NChannel注册到EventLoop的Selector上
* @throws Exception
*/
@Override
protected void doRegister() throws Exception {
boolean selected = false;
for (;;) {
try {
//unwrappedSelector获取eventLoop上的selector,每个EventLoop上都有一个Selector
//但这里为什么设置的感兴趣事件为0呢?Netty权威指南第二版给出的解释如下:
//(1)注册方法是多态的,它既可以被NioServerSocketChannel用来监听客户端的连接接入,也可以注册SocketChannel用来监听网络读写或者写操作
//(2)通过SelectionKey的interestOps(int ops)方法可以方便地修改感兴趣的时间,所以此处注册需要获取SelectionKey并给AbstractNIOChannel的成员变量selectionKey赋值
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
return;
} catch (CancelledKeyException e) {
if (!selected) {
// Force the Selector to select now as the "canceled" SelectionKey may still be
// cached and not removed because no Select.select(..) operation was called yet.
eventLoop().selectNow();
selected = true;
} else {
// We forced a select operation on the selector before but the SelectionKey is still cached
// for whatever reason. JDK bug ?
throw e;
}
}
}
}
doBind0
private static void doBind0(
final ChannelFuture regFuture, final Channel channel,
final SocketAddress localAddress, final ChannelPromise promise) {
// This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up
// the pipeline in its channelRegistered() implementation.
//在Channel的EventLoop中执行Channel的绑定端口逻辑
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
if (regFuture.isSuccess()) {
//注册成功,绑定端口
channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
} else {
//注册失败,回调通知promise失败
promise.setFailure(regFuture.cause());
}
}
});
}
bind
Channel#bind
最终还会进入到io.netty.channel.AbstractChannel.AbstractUnsafe#bind
,
public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
//判断是否在EventLoop线程中,只允许在EventLoop线程中执行,底层就是判断当前执行线程是否和EventLoop对象绑定的线程是同一个线程
assertEventLoop();
if (!promise.setUncancellable() || !ensureOpen(promise)) {
return;
}
// See: https://github.com/netty/netty/issues/576
if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &&
localAddress instanceof InetSocketAddress &&
!((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &&
!PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) {
// Warn a user about the fact that a non-root user can't receive a
// broadcast packet on *nix if the socket is bound on non-wildcard address.
logger.warn(
"A non-root user can't receive a broadcast packet if the socket " +
"is not bound to a wildcard address; binding to a non-wildcard " +
"address (" + localAddress + ") anyway as requested.");
}
//记录Channel是否激活
boolean wasActive = isActive();
try {
//绑定Channel端口,底层会调用Java原生的Channel进行绑定,NioServerSocketChannel实现
doBind(localAddress);
} catch (Throwable t) {
safeSetFailure(promise, t);
closeIfClosed();
return;
}
//如果Channel是激活的,触发Channel已激活事件,这里一般会返回true,
if (!wasActive && isActive()) {
//提交任务,异步执行
invokeLater(new Runnable() {
@Override
public void run() {
pipeline.fireChannelActive();
}
});
}
//回调通知promise成功,回调的是在前边添加的ChannelFutureListener,在创建服务端那里
/**
* ChannelFuture f = b.bind(PORT).addListener(new ChannelFutureListener() {
* @Override
* public void operationComplete(ChannelFuture future) throws Exception {
* System.out.println("测试Channel绑定成功后回调");
* }
* }).sync();
*/
safeSetSuccess(promise);
}
io.netty.channel.socket.nio.NioServerSocketChannel#doBind
protected void doBind(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
//调用Java原生的ServerSocketChannel绑定ip + 端口
javaChannel().bind(localAddress, config.getBacklog());
} else {
javaChannel().socket().bind(localAddress, config.getBacklog());
}
private void invokeLater(Runnable task) {
try {
// This method is used by outbound operation implementations to trigger an inbound event later.
// They do not trigger an inbound event immediately because an outbound operation might have been
// triggered by another inbound event handler method. If fired immediately, the call stack
// will look like this for example:
//
// handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection.
// -> handlerA.ctx.close()
// -> channel.unsafe.close()
// -> handlerA.channelInactive() - (2) another inbound handler method called while in (1) yet
//
// which means the execution of two inbound handler methods of the same handler overlap undesirably.
eventLoop().execute(task);
} catch (RejectedExecutionException e) {
logger.warn("Can't invoke task later as EventLoop rejected it", e);
}
}
beginRead
io.netty.channel.AbstractChannel.AbstractUnsafe#beginRead
io.netty.channel.AbstractChannel.AbstractUnsafe#bind
中如果绑定端口成功,会触发Channel激活事件,此事件会执行到这里,执行流程如下
//AbstractNioMessageChannel
protected void doBeginRead() throws Exception {
if (inputShutdown) {
return;
}
super.doBeginRead();
}
//AbstractNioChannel
protected void doBeginRead() throws Exception {
// Channel.read() or ChannelHandlerContext.read() was called
//获取到当前Channel绑定的SelectionKey
final SelectionKey selectionKey = this.selectionKey;
if (!selectionKey.isValid()) {
return;
}
readPending = true;
final int interestOps = selectionKey.interestOps();
//这里由于在注册Channel到EventLoop时(doRegister),将该Channel感兴趣的事件设置为了0,这里即将开始读了,需要把事件设置回来
//0 & 任何数都是0,readInterestOp又是初始化时设置的OP_ACCEPT,因此这里就是把感兴趣的事件设置为OP_ACCEPT
if ((interestOps & readInterestOp) == 0) {
//设置感兴趣时间为NioServerSocket初始化时设置的OP_ACCEPT,服务端可以开始处理客户端的连接请求了
selectionKey.interestOps(interestOps | readInterestOp);
}
总结
本文我们先熟悉了Netty的服务端的创建流程,了解了整个过程中涉及到的组件,接下来我们会对每个组件进行深入的学习,感兴趣的大家可以关注下我,会持续更新的,谢谢观看。
我是壹氿,感谢各位小伙伴点赞、收藏和评论,文章持续更新,我们下期再见!
也可以加我的个人VX交流沟通:lhj502819,一起努力冲击大厂,另外有很多学习以及面试的材料提供给大家。