溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

59. Netty源代碼分析-ServerBootstrap bind 過程-2

發(fā)布時間:2020-07-27 12:43:21 來源:網(wǎng)絡(luò) 閱讀:811 作者:rongwei84n 欄目:軟件技術(shù)

一. 接上一篇

https://blog.51cto.com/483181/2121265

我們繼續(xù)分析doBind0(regFuture, channel, localAddress, promise)

 private ChannelFuture doBind(final SocketAddress localAddress) {
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
            return regFuture;
        }

        if (regFuture.isDone()) {
            // At this point we know that the registration was complete and successful.
            ChannelPromise promise = channel.newPromise();
            doBind0(regFuture, channel, localAddress, promise); //3. 我們這篇要分析的內(nèi)容
            return promise;
        } else {
            ...
            return promise;
        }
    }

二. doBind0

2.1 4個參數(shù)

如上面代碼,doBind0有4個參數(shù)regFuture, channel, localAddress, promise,它們的類型如下:
regFuture: DefaultChannelPromise
channel:NioServerSocketChannel
localAddress:SocketAddress
promise:DefaultChannelPromise

那繼續(xù)往下面看代碼,

private static void doBind0(
            final ChannelFuture regFuture, final Channel channel,
            final SocketAddress localAddress, final ChannelPromise promise) {

        // This method is invoked before channelRegistered() is triggered.  Give user handlers a chance to set up
        // the pipeline in its channelRegistered() implementation.
        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());
                }
            }
        });
    }

doBind0()代碼很簡單,調(diào)用channel.eventloop()執(zhí)行了一個Runnable。channel.eventloop()調(diào)用的是AbstractChannle.eventloop()

@Override
    public EventLoop eventLoop() {
        EventLoop eventLoop = this.eventLoop;
        if (eventLoop == null) {
            throw new IllegalStateException("channel not registered to an event loop");
        }
        return eventLoop;
    }

而this.eventLoop初始化是在register的時候,具體可以參考上一篇bind初始化的分析

https://blog.51cto.com/483181/2121265

@Override
        public final void register(EventLoop eventLoop, final ChannelPromise promise) {
            ....

            AbstractChannel.this.eventLoop = eventLoop;
                        ...
           }                

它的類型是一個NioEventLoop,所以它就是往自己的線程池里面丟了一個Runnable任務(wù)
NioEventLoop的繼承關(guān)系圖如下:
59. Netty源代碼分析-ServerBootstrap bind 過程-2

我們可以看一下NioEventLoop.execute(Runnable )方法.

2.2 execute(Runnable)方法

這個方法的實現(xiàn)是在SingleThreadEventExecutor.java里面。

private final Queue<Runnable> taskQueue;

@Override
    public void execute(Runnable task) {
        if (task == null) {
            throw new NullPointerException("task");
        }

        boolean inEventLoop = inEventLoop();
        addTask(task);
        if (!inEventLoop) {
            startThread();
            if (isShutdown() && removeTask(task)) {
                reject();
            }
        }

        if (!addTaskWakesUp && wakesUpForTask(task)) {
            wakeup(inEventLoop);
        }
    }

protected void addTask(Runnable task) {
        if (task == null) {
            throw new NullPointerException("task");
        }
        if (!offerTask(task)) {
            reject(task);
        }
    }       

final boolean offerTask(Runnable task) {
        if (isShutdown()) {
            reject();
        }
        return taskQueue.offer(task);
    }       

它是把傳入的Runnable對象放到一個taskQueue隊列里面。

那我們繼續(xù)看Runnable里面的實現(xiàn),channel.bind(xxxx)

channel.eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                             ...
               channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        });

2.3 channel.bind

Channel的類型是NioServerSocketChannel,而bind方法的實現(xiàn)類是在AbstractChannel.java里面.

@Override
    public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
        return pipeline.bind(localAddress, promise);
    }

調(diào)用的是pipeline.bind(xxx),pipeline我們知道,它鏈接了ChannelHandler的Context,有head和tail。head是outbound,tail是inbound.

2.4 pipe.bind(xxx)

DefaultChannelPipeline.java

@Override
    public final ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
        return tail.bind(localAddress, promise);
    }

直接調(diào)用的是tail.bind,繼續(xù)往下面看
AbstractChannelHandlerContext.java

@Override
    public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) {

        final AbstractChannelHandlerContext next = findContextOutbound();
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeBind(localAddress, promise);
        } else {
            safeExecute(executor, new Runnable() {
                @Override
                public void run() {
                    next.invokeBind(localAddress, promise);
                }
            }, promise, null);
        }
        return promise;
    }

private AbstractChannelHandlerContext findContextOutbound() {
        AbstractChannelHandlerContext ctx = this;
        do {
            ctx = ctx.prev;
        } while (!ctx.outbound);
        return ctx;
    }       

它調(diào)用findContextOutbound(),然后調(diào)用它的bind方法,從以前的分析可以知道,outbound講的是head。所以,我們來到head.bind方法

2.5 head.bind

DefaultChannelPipeline.java

@Override
        public void bind(
                ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise)
                throws Exception {
            unsafe.bind(localAddress, promise);
        }

調(diào)用的是unsafe.bind

2.6 unsafe.bind

AbstractChannel.java

@Override
        public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
            assertEventLoop();

            ...

            boolean wasActive = isActive();
            try {
                doBind(localAddress);
            } catch (Throwable t) {
                ...
            }

            if (!wasActive && isActive()) {
                invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        pipeline.fireChannelActive();
                    }
                });
            }

            safeSetSuccess(promise);
        }

繼續(xù)看doBind()

2.7 doBind()

doBind是在NioServerSocketChannel里面

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

這樣就調(diào)用了Java的接口綁定了我們傳入的端口。

這樣bind邏輯整個就分析完了,我們來分析一下整個流程以及類之間的關(guān)系。

三. 總結(jié)

3.1 各個類之間的關(guān)系

  1. EventLoopGroup里面包含若干個EventLoop,具體數(shù)目我們可以手動指定,如果不指定,一般默認就是cpu x 2個。
  2. EventLoop繼承自SingleThreadEventLoop,表示一個線程,里面有個隊列queue,用來存丟過來的Runnable任務(wù).
  3. 我們一般實例化兩個EventLoopGroup,一個是bossGroup,一個是workGroup,bossGroup用來接收客戶端連接,連接可以用channel來描述。然后就把channel丟給workGroup,由workGroup具體負責(zé)這個channel后面的操作。

3.2 對應(yīng)關(guān)系

  1. 一個EventLoopGroup包含多個EventLoop
  2. 一個EventLoop對應(yīng)多個channel,一個channel只對應(yīng)一個EventLoop。EventLoop一般比channel少,好比飯店里面服務(wù)員一般比客人少。所以,也可以想象如果某一個channel上EventLoop做的業(yè)務(wù)邏輯比較復(fù)雜的話,有可能造成來不及相應(yīng)其他channel的請求。
  3. 一個NioServerSocketChannel里面包含一個pipeline,一個unsafe對象
向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI