欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

netty源碼分析之服務(wù)端啟動(dòng)

ServerBootstrap與Bootstrap分別是netty中服務(wù)端與客戶端的引導(dǎo)類,主要負(fù)責(zé)服務(wù)端與客戶端初始化、配置及啟動(dòng)引導(dǎo)等工作,接下來(lái)我們就通過(guò)netty源碼中的示例對(duì)ServerBootstrap與Bootstrap的源碼進(jìn)行一個(gè)簡(jiǎn)單的分析。首先我們知道這兩個(gè)類都繼承自AbstractBootstrap類
netty源碼分析之服務(wù)端啟動(dòng)

發(fā)展壯大離不開(kāi)廣大客戶長(zhǎng)期以來(lái)的信賴與支持,我們將始終秉承“誠(chéng)信為本、服務(wù)至上”的服務(wù)理念,堅(jiān)持“二合一”的優(yōu)良服務(wù)模式,真誠(chéng)服務(wù)每家企業(yè),認(rèn)真做好每個(gè)細(xì)節(jié),不斷完善自我,成就企業(yè),實(shí)現(xiàn)共贏。行業(yè)涉及攪拌罐車等,在重慶網(wǎng)站建設(shè)全網(wǎng)營(yíng)銷推廣、WAP手機(jī)網(wǎng)站、VI設(shè)計(jì)、軟件開(kāi)發(fā)等項(xiàng)目上具有豐富的設(shè)計(jì)經(jīng)驗(yàn)。

接下來(lái)我們就通過(guò)netty源碼中ServerBootstrap的實(shí)例入手對(duì)其進(jìn)行一個(gè)簡(jiǎn)單的分析。

// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
final EchoServerHandler serverHandler = new EchoServerHandler();
try {
//初始化一個(gè)服務(wù)端引導(dǎo)類
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup) //設(shè)置線程組
.channel(NioServerSocketChannel.class)//設(shè)置ServerSocketChannel的IO模型 分為epoll與Nio
.option(ChannelOption.SO_BACKLOG, 100)//設(shè)置option參數(shù),保存成一個(gè)LinkedHashMap<ChannelOption<?>, Object>()
.handler(new LoggingHandler(LogLevel.INFO))//這個(gè)hanlder 只專屬于 ServerSocketChannel 而不是 SocketChannel。
.childHandler(new ChannelInitializer<SocketChannel>() { //這個(gè)handler 將會(huì)在每個(gè)客戶端連接的時(shí)候調(diào)用。供 SocketChannel 使用。@Override
br/>@Override
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. 啟動(dòng)服務(wù)
        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();
    }

            接下來(lái)我們主要從服務(wù)端的socket在哪里初始化與哪里accept連接這兩個(gè)問(wèn)題入手對(duì)netty服務(wù)端啟動(dòng)的流程進(jìn)行分析;

我們首先要知道,netty服務(wù)的啟動(dòng)其實(shí)可以分為以下四步:

創(chuàng)建服務(wù)端Channel
初始化服務(wù)端Channel
注冊(cè)Selector
端口綁定
一、創(chuàng)建服務(wù)端Channel

1、服務(wù)端Channel的創(chuàng)建,主要為以下流程
netty源碼分析之服務(wù)端啟動(dòng)
我們通過(guò)跟蹤代碼能夠看到

final ChannelFuture regFuture = initAndRegister();// 初始化并創(chuàng)建 NioServerSocketChannel

我們?cè)趇nitAndRegister()中可以看到channel的初始化。

channel = channelFactory.newChannel(); // 通過(guò) 反射工廠創(chuàng)建一個(gè) NioServerSocketChannel

我進(jìn)一步看newChannel()中的源碼,在ReflectiveChannelFactory這個(gè)反射工廠中,通過(guò)clazz這個(gè)類的反射創(chuàng)建了一個(gè)服務(wù)端的channel。

@Override
public T newChannel() {
try {
return clazz.getConstructor().newInstance();//反射創(chuàng)建
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + clazz, t);
}
}

    既然通過(guò)反射,我們就要知道clazz類是什么,那么我我們來(lái)看下channelFactory這個(gè)工廠類是在哪里初始化的,初始化的時(shí)候我們傳入了哪個(gè)channel。

這里我們需要看下demo實(shí)例中初始化ServerBootstrap時(shí).channel(NioServerSocketChannel.class)這里的具體實(shí)現(xiàn),我們看下源碼

public B channel(Class<? extends C> channelClass) {
if (channelClass == null) {
throw new NullPointerException("channelClass");
}
return channelFactory(new ReflectiveChannelFactory<C>(channelClass));
}

    通過(guò)上面的代碼我可以直觀的看出正是在這里我們通過(guò)NioServerSocketChannel這個(gè)類構(gòu)造了一個(gè)反射工廠。

那么到這里就很清楚了,我們創(chuàng)建的Channel就是一個(gè)NioServerSocketChannel,那么具體的創(chuàng)建我們就需要看下這個(gè)類的構(gòu)造函數(shù)。首先我們看下一個(gè)NioServerSocketChannel創(chuàng)建的具體流程
netty源碼分析之服務(wù)端啟動(dòng)
首先是newsocket(),我們先看下具體的代碼,在NioServerSocketChannel的構(gòu)造函數(shù)中我們創(chuàng)建了一個(gè)jdk原生的ServerSocketChannel

/**

  • Create a new instance
    */
    public NioServerSocketChannel() {
    this(newSocket(DEFAULT_SELECTOR_PROVIDER));//傳入默認(rèn)的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 <a >#2308</a>.
         */
        return provider.openServerSocketChannel();//可以看到創(chuàng)建的是jdk底層的ServerSocketChannel 
    } catch (IOException e) {
        throw new ChannelException(
                "Failed to open a server socket.", e);
    }
}

    第二步是通過(guò)NioServerSocketChannelConfig配置服務(wù)端Channel的構(gòu)造函數(shù),在代碼中我們可以看到我們把NioServerSocketChannel這個(gè)類傳入到了NioServerSocketChannelConfig的構(gòu)造函數(shù)中進(jìn)行配置

/**

  • Create a new instance using the given {@link ServerSocketChannel}.
    */
    public NioServerSocketChannel(ServerSocketChannel channel) {
    super(null, channel, SelectionKey.OP_ACCEPT);//調(diào)用父類構(gòu)造函數(shù),傳入創(chuàng)建的channel
    config = new NioServerSocketChannelConfig(this, javaChannel().socket());
    }
    第三步在父類AbstractNioChannel的構(gòu)造函數(shù)中把創(chuàng)建服務(wù)端的Channel設(shè)置為非阻塞模式
  /**
  • 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;//這個(gè)ch就是傳入的通過(guò)jdk創(chuàng)建的Channel
    this.readInterestOp = readInterestOp;
    try {
    ch.configureBlocking(false);//設(shè)置為非阻塞
    } 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);
    }
}

    第四步調(diào)用AbstractChannel這個(gè)抽象類的構(gòu)造函數(shù)設(shè)置Channel的id(每個(gè)Channel都有一個(gè)id,唯一標(biāo)識(shí)),unsafe(tcp相關(guān)底層操作),pipeline(邏輯鏈)等,而不管是服務(wù)的Channel還是客戶端的Channel都繼承自這個(gè)抽象類,他們也都會(huì)有上述相應(yīng)的屬性。我們看下AbstractChannel的構(gòu)造函數(shù)
  /**
  • 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();//創(chuàng)建Channel唯一標(biāo)識(shí)
    unsafe = newUnsafe();//netty封裝的TCP 相關(guān)操作類
    pipeline = newChannelPipeline();//邏輯鏈
    }
     2、初始化服務(wù)端創(chuàng)建的Channel
   init(channel);// 初始化這個(gè) NioServerSocketChannel

我們首先列舉下init(channel)中具體都做了哪了些功能:

設(shè)置ChannelOptions、ChannelAttrs ,配置服務(wù)端Channel的相關(guān)屬性;
設(shè)置ChildOptions、ChildAttrs,配置每個(gè)新連接的Channel的相關(guān)屬性;
Config handler,配置服務(wù)端pipeline;
add ServerBootstrapAcceptor,添加連接器,對(duì)accpet接受到的新連接進(jìn)行處理,添加一個(gè)nio線程;
那么接下來(lái)我們通過(guò)代碼,對(duì)每一步設(shè)置進(jìn)行一下分析:

首先是在SeverBootstrap的init()方法中對(duì)ChannelOptions、ChannelAttrs 的配置的關(guān)鍵代碼

final Map<ChannelOption<?>, Object> options = options0();//拿到你設(shè)置的option
synchronized (options) {
setChannelOptions(channel, options, logger);//設(shè)置NioServerSocketChannel相應(yīng)的TCP參數(shù),其實(shí)這一步就是把options設(shè)置到channel的config中
}

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

            然后是對(duì)ChildOptions、ChildAttrs配置的關(guān)鍵代碼
          //可以看到兩個(gè)都是局部變量,會(huì)在下面設(shè)置pipeline時(shí)用到

final Entry<ChannelOption<?>, Object>[] currentChildOptions;
final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
synchronized (childOptions) {
currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0));
}
synchronized (childAttrs) {
currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0));
}

            第三步對(duì)服務(wù)端Channel的handler進(jìn)行配置

p.addLast(new ChannelInitializer<Channel>() {@Override
br/>@Override
final ChannelPipeline pipeline = ch.pipeline();
ChannelHandler handler = config.handler();//拿到我們自定義的hanler
if (handler != null) {
pipeline.addLast(handler);
}

            ch.eventLoop().execute(new Runnable() {
                @Override
                public void run() {
                    pipeline.addLast(new ServerBootstrapAcceptor(
                            ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                }
            });
        }
    });

            第四步添加ServerBootstrapAcceptor連接器,這個(gè)是netty向服務(wù)端Channel自定義添加的一個(gè)handler,用來(lái)處理新連接的添加與屬性配置,我們來(lái)看下關(guān)鍵代碼
          ch.eventLoop().execute(new Runnable() {

@Override
public void run() {
//在這里會(huì)把我們自定義的ChildGroup、ChildHandler、ChildOptions、ChildAttrs相關(guān)配置傳入到ServerBootstrapAcceptor構(gòu)造函數(shù)中,并綁定到新的連接上
pipeline.addLast(new ServerBootstrapAcceptor(
ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});

三、注冊(cè)Selector

一個(gè)服務(wù)端的Channel創(chuàng)建完畢后,下一步就是要把它注冊(cè)到一個(gè)事件輪詢器Selector上,在initAndRegister()中我們把上面初始化的Channel進(jìn)行注冊(cè)

ChannelFuture regFuture = config().group().register(channel);//注冊(cè)我們已經(jīng)初始化過(guò)的Channel
而這個(gè)register具體實(shí)現(xiàn)是在AbstractChannel中的AbstractUnsafe抽象類中的
/**

  • 1、先是一系列的判斷。
  • 2、判斷當(dāng)前線程是否是給定的 eventLoop 線程。注意:這點(diǎn)很重要,Netty 線程模型的高性能取決于對(duì)于當(dāng)前執(zhí)行的Thread 的身份的確定。如果不在當(dāng)前線程,那么就需要很多同步措施(比如加鎖),上下文切換等耗費(fèi)性能的操作。
  • 3、異步(因?yàn)槲覀冞@里直到現(xiàn)在還是 main 線程在執(zhí)行,不屬于當(dāng)前線程)的執(zhí)行 register0 方法。*/
    @Override
    br/>*/
    @Override
    if (eventLoop == null) {
    throw new NullPointerException("eventLoop");
    }
    if (isRegistered()) {
    promise.setFailure(new IllegalStateException("registered to an event loop already"));
    return;
    }
    if (!isCompatible(eventLoop)) {
    promise.setFailure(
    new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
    return;
    }
        AbstractChannel.this.eventLoop = eventLoop;//綁定線程

        if (eventLoop.inEventLoop()) {
            register0(promise);//實(shí)際的注冊(cè)過(guò)程
        } 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);
                closeForcibly();
                closeFuture.setClosed();
                safeSetFailure(promise, t);
            }
        }
    }

首先我們對(duì)整個(gè)注冊(cè)的流程做一個(gè)梳理
netty源碼分析之服務(wù)端啟動(dòng)
接下來(lái)我們進(jìn)入register0()方法看下注冊(cè)過(guò)程的具體實(shí)現(xiàn)

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)) {
return;
}
boolean firstRegistration = neverRegistered;
doRegister();//jdk channel的底層注冊(cè)
neverRegistered = false;
registered = true;

            // 觸發(fā)綁定的handler事件
            // 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.
            pipeline.invokeHandlerAddedIfNeeded();

            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.
            closeForcibly();
            closeFuture.setClosed();
            safeSetFailure(promise, t);
        }
    }
AbstractNioChannel中doRegister()的具體實(shí)現(xiàn)就是把jdk底層的channel綁定到eventLoop的selecor上

@Override
protected void doRegister() throws Exception {
boolean selected = false;
for (;;) {
try {
//把channel注冊(cè)到eventLoop上的selector上
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;
}
}
}
}

    到這里netty就把服務(wù)端的channel注冊(cè)到了指定的selector上,下面就是服務(wù)端口的邦迪

三、端口綁定

首先我們梳理下netty中服務(wù)端口綁定的流程
netty源碼分析之服務(wù)端啟動(dòng)
我們來(lái)看下AbstarctUnsafe中bind()方法的具體實(shí)現(xiàn)

@Override
public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
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.");
        }

        boolean wasActive = isActive();//判斷綁定是否完成
        try {
            doBind(localAddress);//底層jdk綁定端口
        } catch (Throwable t) {
            safeSetFailure(promise, t);
            closeIfClosed();
            return;
        }

        if (!wasActive && isActive()) {
            invokeLater(new Runnable() {
                @Override
                public void run() {
                    pipeline.fireChannelActive();//觸發(fā)ChannelActive事件
                }
            });
        }

        safeSetSuccess(promise);
    }

            在doBind(localAddress)中netty實(shí)現(xiàn)了jdk底層端口的綁定
          @Override

protected void doBind(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
javaChannel().bind(localAddress, config.getBacklog());
} else {
javaChannel().socket().bind(localAddress, config.getBacklog());
}
}

在 pipeline.fireChannelActive()中會(huì)觸發(fā)pipeline中的channelActive()方法

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelActive();

        readIfIsAutoRead();
    }

在channelActive中首先會(huì)把ChannelActive事件往下傳播,然后調(diào)用readIfIsAutoRead()方法出觸發(fā)channel的read事件,而它最終調(diào)用AbstractNioChannel中的doBeginRead()方法

@Override
protected void doBeginRead() throws Exception {
// Channel.read() or ChannelHandlerContext.read() was called
final SelectionKey selectionKey = this.selectionKey;
if (!selectionKey.isValid()) {
return;
}

    readPending = true;

    final int interestOps = selectionKey.interestOps();
    if ((interestOps & readInterestOp) == 0) {
        selectionKey.interestOps(interestOps | readInterestOp);//readInterestOp為  SelectionKey.OP_ACCEPT
    }
}

在doBeginRead()方法,netty會(huì)把a(bǔ)ccept事件注冊(cè)到Selector上。

到此我們對(duì)netty服務(wù)端的啟動(dòng)流程有了一個(gè)大致的了解,整體可以概括為下面四步:

1、channelFactory.newChannel(),其實(shí)就是創(chuàng)建jdk底層channel,并初始化id、piepline等屬性;

2、init(channel),添加option、attr等屬性,并添加ServerBootstrapAcceptor連接器;

3、config().group().register(channel),把jdk底層的channel注冊(cè)到eventLoop上的selector上;

4、doBind0(regFuture, channel, localAddress, promise),完成服務(wù)端端口的監(jiān)聽(tīng),并把a(bǔ)ccept事件注冊(cè)到selector上;

以上就是對(duì)netty服務(wù)端啟動(dòng)流程進(jìn)行的一個(gè)簡(jiǎn)單分析,有很多細(xì)節(jié)沒(méi)有關(guān)注與深入,其中如有不足與不正確的地方還望指出與海涵。

文章題目:netty源碼分析之服務(wù)端啟動(dòng)
當(dāng)前網(wǎng)址:http://chinadenli.net/article12/ggjigc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)網(wǎng)站設(shè)計(jì)公司全網(wǎng)營(yíng)銷推廣品牌網(wǎng)站制作小程序開(kāi)發(fā)網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護(hù)公司