通过前面的几篇文章,对整个netty部分的架构已经运行原理都有了一定的了解,那么这篇文章来分析一个经常用到的类:ServerBootstrap,一般对于服务器端的编程它用到的都还算是比较的多。。看一看它的初始化,以及它的运行原理。。。
首先我们还是引入一段代码,通过分析这段代码来分析ServerBootstrap的运行。。。
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup);
- b.channel(NioServerSocketChannel.class);
- b.childHandler(new ChannelInitializer<SocketChannel>(){
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
-
- ch.pipeline().addLast(new MyChannelHandler());
- }
-
- });
-
-
- ChannelFuture f = b.bind(80).sync();
- f.channel().closeFuture().sync();
- } finally {
- bossGroup.shutdownGracefully();
- workerGroup.shutdownGracefully();
- }
这段代码在前面的文章也有用到,基本上其意思也都在上面的注释中说的比较清楚了,那么我们接下来具体的分析其中的方法调用,首先是ServerBootstrap的group方法:
- public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {
- super.group(parentGroup);
- if (childGroup == null) {
- throw new NullPointerException("childGroup");
- }
- if (this.childGroup != null) {
- throw new IllegalStateException("childGroup set already");
- }
- this.childGroup = childGroup;
- return this;
- }
这个方法是用来设置eventloopgroup,首先调用了父类的group方法(abstractbootstrap),就不将父类的方法列出来了,其实意思都差不多,eventloopgroup属性的值。。。
好了,接下来我们再来看一下channel方法:
- public B channel(Class<? extends C> channelClass) {
- if (channelClass == null) {
- throw new NullPointerException("channelClass");
- }
- return channelFactory(new BootstrapChannelFactory<C>(channelClass));
- }
-
- @SuppressWarnings("unchecked")
- public B channelFactory(ChannelFactory<? extends C> channelFactory) {
- if (channelFactory == null) {
- throw new NullPointerException("channelFactory");
- }
- if (this.channelFactory != null) {
- throw new IllegalStateException("channelFactory set already");
- }
-
- this.channelFactory = channelFactory;
- return (B) this;
- }
该方法主要是用于构造用于产生channel的工厂类,在我们这段代码说白了就是用于实例化serversocketchannel的工厂类。。。
接下来我们再来看一下childHandler方法:
- public ServerBootstrap childHandler(ChannelHandler childHandler) {
- if (childHandler == null) {
- throw new NullPointerException("childHandler");
- }
- this.childHandler = childHandler;
- return this;
- }
这个很简单吧,就是一个赋值,具体说他有什么用,前面的注释有说明,不过以后的分析会说明它有什么用的。。。
接下来我们来看一下bind方法,这个比较重要吧:
- public ChannelFuture bind(int inetPort) {
- return bind(new InetSocketAddress(inetPort));
- }
好吧,接下来再来看bind方法:
- public ChannelFuture bind(SocketAddress localAddress) {
- validate();
- if (localAddress == null) {
- throw new NullPointerException("localAddress");
- }
- return doBind(localAddress);
- }
好吧,再来看看doBind方法:
- private ChannelFuture doBind(final SocketAddress localAddress) {
- final ChannelFuture regPromise = initAndRegister();
- final Channel channel = regPromise.channel();
- final ChannelPromise promise = channel.newPromise();
- if (regPromise.isDone()) {
- doBind0(regPromise, channel, localAddress, promise);
- } else {
- regPromise.addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture future) throws Exception {
- doBind0(future, channel, localAddress, promise);
- }
- });
- }
-
- return promise;
- }
这里调用了一个比较重要的方法:initAndRegister,我们来看看它的定义:
- final ChannelFuture initAndRegister() {
-
- final Channel channel = channelFactory().newChannel();
- try {
- init(channel);
- } catch (Throwable t) {
- channel.unsafe().closeForcibly();
- return channel.newFailedFuture(t);
- }
-
- ChannelPromise regPromise = channel.newPromise();
- group().register(channel, regPromise);
- if (regPromise.cause() != null) {
- if (channel.isRegistered()) {
- channel.close();
- } else {
- channel.unsafe().closeForcibly();
- }
- }
-
-
-
-
-
-
-
-
-
-
- return regPromise;
- }
代码还是很简单,而且也相对比较好理解,无非就是利用前面说到过的channel工厂类来创建一个serversocketchannel,然后调用init方法对这个刚刚生成的channel进行一些初始化的操作,然后在调用eventloopgroup的register方法,将当前这个channel的注册到group上,那么以后这个channel的事件都在这个group上面执行,说白了也就是一些accept。、。。
好,我们先来看看这个init方法吧:
- @Override
- void init(Channel channel) throws Exception {
-
- final Map<ChannelOption<?>, Object> options = options();
- synchronized (options) {
- channel.config().setOptions(options);
- }
-
- final Map<AttributeKey<?>, Object> attrs = attrs();
- synchronized (attrs) {
- for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
- @SuppressWarnings("unchecked")
- AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
- channel.attr(key).set(e.getValue());
- }
- }
-
-
- ChannelPipeline p = channel.pipeline();
- if (handler() != null) {
- p.addLast(handler());
- }
-
- final EventLoopGroup currentChildGroup = childGroup;
- final ChannelHandler currentChildHandler = childHandler;
- final Entry<ChannelOption<?>, Object>[] currentChildOptions;
- final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
- synchronized (childOptions) {
- currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
- }
- synchronized (childAttrs) {
- currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
- }
-
- p.addLast(new ChannelInitializer<Channel>() {
- @Override
- public void initChannel(Channel ch) throws Exception {
-
- ch.pipeline().addLast(new ServerBootstrapAcceptor(
- currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
- }
- });
- }
代码还是相对很简单,首先初始化一些配置参数,然后初始化属性,最后还要为当前的channel的pipeline添加一个handler,这个handler用来当channel注册到eventloop上面之后对其进行一些初始化,我们还是来看看channelInitalizer的定义吧:
- public abstract class ChannelInitializer<C extends Channel> extends ChannelStateHandlerAdapter {
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChannelInitializer.class);
-
-
- protected abstract void initChannel(C ch) throws Exception;
-
- @SuppressWarnings("unchecked")
- @Override
- public final void channelRegistered(ChannelHandlerContext ctx)
- throws Exception {
- boolean removed = false;
- boolean success = false;
- try {
-
- initChannel((C) ctx.channel());
- ctx.pipeline().remove(this);
- removed = true;
- ctx.fireChannelRegistered();
- success = true;
- } catch (Throwable t) {
- logger.warn("Failed to initialize a channel. Closing: " + ctx.channel(), t);
- } finally {
- if (!removed) {
- ctx.pipeline().remove(this);
- }
- if (!success) {
- ctx.close();
- }
- }
- }
-
- @Override
- public void inboundBufferUpdated(ChannelHandlerContext ctx) throws Exception {
- ctx.fireInboundBufferUpdated();
- }
- }
它有一个channelRegistered方法,这个方法是在当前pipeline所属的channel注册到eventloop上面之后会激活的方法,它则是调用了用户自定义的函数来初始化channel,然后在将当前handler移除。。。也就是执行
- ch.pipeline().addLast(new ServerBootstrapAcceptor(
- currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
这里又为当前的serversocketchannel添加了另外一个handler,来看看该类型的定义吧:
- private static class ServerBootstrapAcceptor
- extends ChannelStateHandlerAdapter implements ChannelInboundMessageHandler<Channel> {
-
- private final EventLoopGroup childGroup;
- private final ChannelHandler childHandler;
- private final Entry<ChannelOption<?>, Object>[] childOptions;
- private final Entry<AttributeKey<?>, Object>[] childAttrs;
-
- @SuppressWarnings("unchecked")
- ServerBootstrapAcceptor(
- EventLoopGroup childGroup, ChannelHandler childHandler,
- Entry<ChannelOption<?>, Object>[] childOptions, Entry<AttributeKey<?>, Object>[] childAttrs) {
- this.childGroup = childGroup;
- this.childHandler = childHandler;
- this.childOptions = childOptions;
- this.childAttrs = childAttrs;
- }
-
- @Override
- public MessageBuf<Channel> newInboundBuffer(ChannelHandlerContext ctx) throws Exception {
- return Unpooled.messageBuffer();
- }
-
- @Override
- @SuppressWarnings("unchecked")
-
- public void inboundBufferUpdated(ChannelHandlerContext ctx) {
- MessageBuf<Channel> in = ctx.inboundMessageBuffer();
- for (;;) {
- Channel child = in.poll();
- if (child == null) {
- break;
- }
-
- child.pipeline().addLast(childHandler);
-
- for (Entry<ChannelOption<?>, Object> e: childOptions) {
- try {
- if (!child.config().setOption((ChannelOption<Object>) e.getKey(), e.getValue())) {
- logger.warn("Unknown channel option: " + e);
- }
- } catch (Throwable t) {
- logger.warn("Failed to set a channel option: " + child, t);
- }
- }
-
- for (Entry<AttributeKey<?>, Object> e: childAttrs) {
- child.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
- }
-
- try {
- childGroup.register(child);
- } catch (Throwable t) {
- child.unsafe().closeForcibly();
- logger.warn("Failed to register an accepted channel: " + child, t);
- }
- }
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- final ChannelConfig config = ctx.channel().config();
- if (config.isAutoRead()) {
-
-
- config.setAutoRead(false);
- ctx.channel().eventLoop().schedule(new Runnable() {
- @Override
- public void run() {
- config.setAutoRead(true);
- }
- }, 1, TimeUnit.SECONDS);
- }
-
-
- ctx.fireExceptionCaught(cause);
- }
- }
主要是有一个比较重要的方法,inboundBufferUpdated,这个方法是在有数据进来的时候会调用的,用于处理进来的数据,也就是accept到的channel,这里就知道我们定义的chidHandler的用处了吧,netty会将这个handler直接加入到刚刚accept到的channel的pipeline上面去。。。最后还要讲当前accept到的channel注册到child eventloop上面去,这里也就完完全全的明白了最开始定义的两个eventloopgroup的作用了。。。
好了,serversocketchannel的init以及register差不多了,然后会调用doBind0方法,将当前的serversocketchannel绑定到一个本地端口,
- private static void doBind0(
- final ChannelFuture regFuture, final Channel channel,
- final SocketAddress localAddress, final ChannelPromise promise) {
-
-
-
-
- channel.eventLoop().execute(new Runnable() {
- @Override
-
- public void run() {
- if (regFuture.isSuccess()) {
-
-
- channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
- } else {
- promise.setFailure(regFuture.cause());
- }
- }
- });
- }
其实这里调用bind方法最终还是调用serversocketchannel的unsafe对象的bind方法。。。。
到这里,整个serverbootstrap 就算初始化完成了,而且也可以开始运行了。。。
- b.childHandler(new ChannelInitializer<SocketChannel>(){
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
-
- ch.pipeline().addLast(new MyChannelHandler());
- }
-
- });
这段代码的意思是对于刚刚accept到的channel,将会在它的pipeline上面添加handler,这个handler的用处主要是就是用户自定义的initChannel方法,就是初始化这个channel,说白了就是为它的pipeline上面添加自己定义的handler。。。
这样整个serverbootstrap是怎么运行的也就差不多了。。。
刚开始接触到netty的时候觉得这里一头雾水,通过这段时间对其代码的阅读,总算搞懂了其整个运行的原理,而且觉得其设计还是很漂亮的,虽然有的时候会觉得有那么一点点的繁琐。。。。
整个运行过程总结为一下几个步骤:
(1)创建用于两个eventloopgroup对象,一个用于管理serversocketchannel,一个用于管理accept到的channel
(2)创建serverbootstrap对象,
(3)设置eventloopgroup
(4)创建用于构建用到的channel的工厂类
(5)设置childhandler,它的主要功能主要是用户定义代码来初始化accept到的channel
(6)创建serversocketchannel,并对它进行初始化,绑定端口,以及register,并为serversocketchannel的pipeline设置默认的handler
通过这几个步骤,整个serverbootstrap也就算是运行起来了。。。