經過前面的幾篇文章,對整個netty部分的架構已經運行原理都有了必定的瞭解,那麼這篇文章來分析一個常常用到的類:ServerBootstrap,通常對於服務器端的編程它用到的都還算是比較的多。。看一看它的初始化,以及它的運行原理。。。java
首先咱們仍是引入一段代碼,經過分析這段代碼來分析ServerBootstrap的運行。。。git
- 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方法:github
- 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方法:bootstrap
- 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的工廠類。。。promise
接下來咱們再來看一下childHandler方法:服務器
- public ServerBootstrap childHandler(ChannelHandler childHandler) {
- if (childHandler == null) {
- throw new NullPointerException("childHandler");
- }
- this.childHandler = childHandler;
- return this;
- }
這個很簡單吧,就是一個賦值,具體說他有什麼用,前面的註釋有說明,不過之後的分析會說明它有什麼用的。。。架構
接下來咱們來看一下bind方法,這個比較重要吧:socket
- public ChannelFuture bind(int inetPort) {
- return bind(new InetSocketAddress(inetPort));
- }
好吧,接下來再來看bind方法:ide
- 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也就算是運行起來了。。。