Netty4源碼分析-ServerBootstrap

ServerBootstrap與Bootstrap類似硕盹,只不過這個(gè)是用于服務(wù)端的啟動(dòng)温赔。下面看下具體的使用:

public class TimeServer {

    public void bind(int port) throws Exception {
        // 配置服務(wù)端的NIO線程組
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChildChannelHandler());
            // 綁定端口况木,同步等待成功
            ChannelFuture f = b.bind(port).sync();

            // 等待服務(wù)端監(jiān)聽端口關(guān)閉
            f.channel().closeFuture().sync();
        } finally {
            // 優(yōu)雅退出咐蚯,釋放線程池資源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel arg0) throws Exception {
            arg0.pipeline().addLast(new TimeServerHandler());
        }

    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默認(rèn)值
            }
        }
        new TimeServer().bind(port);
    }
}

與上篇文章介紹的Bootstrap不同乃坤,這里傳入了兩個(gè)EventLoopGroup撞蜂,其中bossGroup用于接收請(qǐng)求,workerGroup用于處理IO事件侥袜。Netty是Reactor模式的實(shí)現(xiàn)蝌诡,有關(guān)Reactor模式請(qǐng)參考NIO技術(shù)概覽

這里傳入的Channel類型是NioServerSocketChannel枫吧,與Bootstrap一樣浦旱,在bind方法中會(huì)調(diào)用init方法,下面看下ServerBootstrap中init方法的實(shí)現(xiàn):

@Override
void init(Channel channel) throws Exception {
    final Map<ChannelOption<?>, Object> options = options0();
    synchronized (options) {
        setChannelOptions(channel, options, logger);
    }

    final Map<AttributeKey<?>, Object> attrs = attrs0();
    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();

    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()));
    }

    // 向pipeLine中添加Handler
    p.addLast(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            ChannelHandler handler = config.handler();
            if (handler != null) {
                pipeline.addLast(handler);
            }
            // 使用eventLoop來執(zhí)行任務(wù)
            ch.eventLoop().execute(new Runnable() {
                @Override
                public void run() {
                    pipeline.addLast(new ServerBootstrapAcceptor(
                            ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                }
            });
        }
    });
}

注意一下這段代碼:

pipeline.addLast(new ServerBootstrapAcceptor(
        ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));

這段代碼向pipeLine中添加了一個(gè)ServerBootstrapAcceptor對(duì)象九杂,ServerBootstrapAcceptor對(duì)象也是一個(gè)Handler颁湖,看下ServerBootstrapAcceptor的定義:

private static class ServerBootstrapAcceptor extends ChannelInboundHandlerAdapter {

    private final EventLoopGroup childGroup;
    private final ChannelHandler childHandler;
    private final Entry<ChannelOption<?>, Object>[] childOptions;
    private final Entry<AttributeKey<?>, Object>[] childAttrs;
    private final Runnable enableAutoReadTask;

    ServerBootstrapAcceptor(
            final Channel channel, EventLoopGroup childGroup, ChannelHandler childHandler,
            Entry<ChannelOption<?>, Object>[] childOptions, Entry<AttributeKey<?>, Object>[] childAttrs) {
        this.childGroup = childGroup;
        this.childHandler = childHandler;
        this.childOptions = childOptions;
        this.childAttrs = childAttrs;

        // Task which is scheduled to re-enable auto-read.
        // It's important to create this Runnable before we try to submit it as otherwise the URLClassLoader may
        // not be able to load the class because of the file limit it already reached.
        //
        // See https://github.com/netty/netty/issues/1328
        enableAutoReadTask = new Runnable() {
            @Override
            public void run() {
                channel.config().setAutoRead(true);
            }
        };
    }

    @Override
    @SuppressWarnings("unchecked")
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        final Channel child = (Channel) msg;

        child.pipeline().addLast(childHandler);

        setChannelOptions(child, childOptions, logger);

        for (Entry<AttributeKey<?>, Object> e: childAttrs) {
            child.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
        }

        try {
            childGroup.register(child).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        forceClose(child, future.cause());
                    }
                }
            });
        } catch (Throwable t) {
            forceClose(child, t);
        }
    }

    private static void forceClose(Channel child, 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()) {
            // stop accept new connections for 1 second to allow the channel to recover
            // See https://github.com/netty/netty/issues/1328
            config.setAutoRead(false);
            ctx.channel().eventLoop().schedule(enableAutoReadTask, 1, TimeUnit.SECONDS);
        }
        // still let the exceptionCaught event flow through the pipeline to give the user
        // a chance to do something with it
        ctx.fireExceptionCaught(cause);
    }
}

ServerBootstrapAcceptor繼承自ChannelInboundHandlerAdapter,用于處理Inbound事件例隆,該類的主要功能就是在服務(wù)器端接收到請(qǐng)求之后甥捺,會(huì)返回一個(gè)NioSocketChannel對(duì)象作為參數(shù)msg傳入channelRead方法中,用變量child來表示镀层;然后把在TimeServer中傳入的childHandler添加到child所對(duì)應(yīng)的pipeLine中镰禾,然后把child注冊(cè)到childGroup中,也就是TimeServer中定義的workerGroup。

接收請(qǐng)求的操作是在NioServerSocketChannel中的doReadMessages方法中實(shí)現(xiàn)的:

@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    SocketChannel ch = SocketUtils.accept(javaChannel());

    try {
        if (ch != null) {
            buf.add(new NioSocketChannel(this, ch));
            return 1;
        }
    } catch (Throwable t) {
        logger.warn("Failed to create a new channel from an accepted socket.", t);

        try {
            ch.close();
        } catch (Throwable t2) {
            logger.warn("Failed to close a socket.", t2);
        }
    }

    return 0;
}

doReadMessages方法在NioMessageUnsafe中的read方法中調(diào)用吴侦,然后會(huì)執(zhí)行pipeline.fireChannelRead(readBuf.get(i));將SocketChannel對(duì)象傳入屋休,也就是channelRead方法中的msg參數(shù)。至此备韧,一個(gè)請(qǐng)求已經(jīng)接收完畢劫樟,通道之間的通信就會(huì)交給childGroup,也就是TimeServer中的workerGroup來處理织堂。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末叠艳,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子易阳,更是在濱河造成了極大的恐慌附较,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,843評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件闽烙,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡声搁,警方通過查閱死者的電腦和手機(jī)黑竞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疏旨,“玉大人很魂,你說我怎么就攤上這事¢芾裕” “怎么了遏匆?”我有些...
    開封第一講書人閱讀 163,187評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長谁榜。 經(jīng)常有香客問我幅聘,道長,這世上最難降的妖魔是什么窃植? 我笑而不...
    開封第一講書人閱讀 58,264評(píng)論 1 292
  • 正文 為了忘掉前任帝蒿,我火速辦了婚禮,結(jié)果婚禮上巷怜,老公的妹妹穿的比我還像新娘葛超。我一直安慰自己,他們只是感情好延塑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,289評(píng)論 6 390
  • 文/花漫 我一把揭開白布绣张。 她就那樣靜靜地躺著,像睡著了一般关带。 火紅的嫁衣襯著肌膚如雪侥涵。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,231評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音独令,去河邊找鬼端朵。 笑死,一個(gè)胖子當(dāng)著我的面吹牛燃箭,可吹牛的內(nèi)容都是我干的冲呢。 我是一名探鬼主播,決...
    沈念sama閱讀 40,116評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼招狸,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼敬拓!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起裙戏,我...
    開封第一講書人閱讀 38,945評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤乘凸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后累榜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體营勤,經(jīng)...
    沈念sama閱讀 45,367評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,581評(píng)論 2 333
  • 正文 我和宋清朗相戀三年壹罚,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了葛作。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,754評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡猖凛,死狀恐怖赂蠢,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情辨泳,我是刑警寧澤虱岂,帶...
    沈念sama閱讀 35,458評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站菠红,受9級(jí)特大地震影響第岖,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜试溯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,068評(píng)論 3 327
  • 文/蒙蒙 一绍傲、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧耍共,春花似錦烫饼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至钩骇,卻和暖如春比藻,著一層夾襖步出監(jiān)牢的瞬間铝量,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評(píng)論 1 269
  • 我被黑心中介騙來泰國打工银亲, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留慢叨,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,797評(píng)論 2 369
  • 正文 我出身青樓务蝠,卻偏偏與公主長得像拍谐,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子馏段,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,654評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容