ServerBootstrap与Bootstrap分别是netty中服务端与客户端的引导类,主要负责服务端与客户端初始化、配置及启动引导等工作,接下来我们就通过netty源码中的示例对ServerBootstrap与Bootstrap的源码进行一个简单的分析。首先我们知道这两个类都继承自AbstractBootstrap类
接下来我们就通过netty源码中ServerBootstrap的实例入手对其进行一个简单的分析。
复制代码
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
final EchoServerHandler serverHandler = new EchoServerHandler();
try {
//初始化一个服务端引导类
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup) //设置线程组
.channel(NioServerSocketChannel.class)//设置ServerSocketChannel的IO模型 分为epoll与Nio
.option(ChannelOption.SO_BACKLOG, 100)//设置option参数,保存成一个LinkedHashMap, Object>()
.handler(new LoggingHandler(LogLevel.INFO))//这个hanlder 只专属于 ServerSocketChannel 而不是 SocketChannel。
.childHandler(new ChannelInitializer() { //这个handler 将会在每个客户端连接的时候调用。供 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).sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
复制代码
接下来我们主要从服务端的socket在哪里初始化与哪里accept连接这两个问题入手对netty服务端启动的流程进行分析;
我们首先要知道,netty服务的启动其实可以分为以下四步:
创建服务端Channel
初始化服务端Channel
注册Selector
端口绑定
一、创建服务端Channel
1、服务端Channel的创建,主要为以下流程
我们通过跟踪代码能够看到
final ChannelFuture regFuture = initAndRegister();// 初始化并创建 NioServerSocketChannel
我们在initAndRegister()中可以看到channel的初始化。
channel = channelFactory.newChannel(); // 通过 反射工厂创建一个 NioServerSocketChannel
我进一步看newChannel()中的源码,在ReflectiveChannelFactory这个反射工厂中,通过clazz这个类的反射创建了一个服务端的channel。
复制代码
@Override
public T newChannel() {
try {
return clazz.getConstructor().newInstance();//反射创建
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + clazz, t);
}
}
复制代码
既然通过反射,我们就要知道clazz类是什么,那么我我们来看下channelFactory这个工厂类是在哪里初始化的,初始化的时候我们传入了哪个channel。
这里我们需要看下demo实例中初始化ServerBootstrap时.channel(NioServerSocketChannel.class)这里的具体实现,我们看下源码
复制代码
public B channel(Class extends C> channelClass) {
if (channelClass == null) {
throw new NullPointerException("channelClass");
}
return channelFactory(new ReflectiveChannelFactory(channelClass));
}
复制代码
通过上面的代码我可以直观的看出正是在这里我们通过NioServerSocketChannel这个类构造了一个反射工厂。
那么到这里就很清楚了,我们创建的Channel就是一个NioServerSocketChannel,那么具体的创建我们就需要看下这个类的构造函数。首先我们看下一个NioServerSocketChannel创建的具体流程
首先是newsocket(),我们先看下具体的代码,在NioServerSocketChannel的构造函数中我们创建了一个jdk原生的ServerSocketChannel
复制代码
/**
* Create a new instance
*/
public NioServerSocketChannel() {
this(newSocket(DEFAULT_SELECTOR_PROVIDER));//传入默认的SelectorProvider
}
private static ServerSocketChannel newSocket(SelectorProvider provider) {
try {
/**
* Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
* {@link SelectorProvider#provider()} which is called by each ServerSocketChannel.open() otherwise.
*
* See #2308.
*/
return provider.openServerSocketChannel();//可以看到创建的是jdk底层的ServerSocketChannel
} catch (IOException e) {
throw new ChannelException(
"Failed to open a server socket.", e);
}
}
复制代码
第二步是通过NioServerSocketChannelConfig配置服务端Channel的构造函数,在代码中我们可以看到我们把NioServerSocketChannel这个类传入到了NioServerSocketChannelConfig的构造函数中进行配置
复制代码
/**
* Create a new instance using the given {@link ServerSocketChannel}.
*/
public NioServerSocketChannel(ServerSocketChannel channel) {
super(null, channel, SelectionKey.OP_ACCEPT);//调用父类构造函数,传入创建的channel
config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}
复制代码
第三步在父类AbstractNioChannel的构造函数中把创建服务端的Channel设置为非阻塞模式
复制代码
/**
* Create a new instance
*
* @param parent the parent {@link Channel} by which this instance was created. May be {@code null}
* @param ch the underlying {@link SelectableChannel} on which it operates
* @param readInterestOp the ops to set to receive data from the {@link SelectableChannel}
*/
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch;//这个ch就是传入的通过jdk创建的Channel
this.readInterestOp = readInterestOp;
try {
ch.configureBlocking(false);//设置为非阻塞
} catch (IOException e) {
try {
ch.close();
} catch (IOException e2) {
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
}
}
throw new ChannelException("Failed to enter non-blocking mode.", e);
}
}
复制代码
第四步调用AbstractChannel这个抽象类的构造函数设置Channel的id(每个Channel都有一个id,唯一标识),unsafe(tcp相关底层操作),pipeline(逻辑链)等,而不管是服务的Channel还是客户端的Channel都继承自这个抽象类,他们也都会有上述相应的属性。我们看下AbstractChannel的构造函数
复制代码
/**
* 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;
id = newId();//创建Channel唯一标识
unsafe = newUnsafe();//netty封装的TCP 相关操作类
pipeline = newChannelPipeline();//逻辑链
}
复制代码
2、初始化服务端创建的Channel
init(channel);// 初始化这个 NioServerSocketChannel
我们首先列举下init(channel)中具体都做了哪了些功能:
设置ChannelOptions、ChannelAttrs ,配置服务端Channel的相关属性;
设置ChildOptions、ChildAttrs,配置每个新连接的Channel的相关属性;
Config handler,配置服务端pipeline;
add ServerBootstrapAcceptor,添加连接器,对accpet接受到的新连接进行处理,添加一个nio线程;
那么接下来我们通过代码,对每一步设置进行一下分析:
首先是在SeverBootstrap的init()方法中对ChannelOptions、ChannelAttrs 的配置的关键代码
复制代码
final Map, Object> options = options0();//拿到你设置的option
synchronized (options) {
setChannelOptions(channel, options, logger);//设置NioServerSocketChannel相应的TCP参数,其实这一步就是把options设置到channel的config中
}
final Map, Object> attrs = attrs0();
synchronized (attrs) {
for (Entry, Object> e: attrs.entrySet()) {
@SuppressWarnings("unchecked")
AttributeKey