服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - netty服务端辅助类ServerBootstrap创建逻辑分析

netty服务端辅助类ServerBootstrap创建逻辑分析

2022-10-21 15:54liron Java教程

这篇文章主要介绍了netty服务端辅助类ServerBootstrap创建逻辑分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

ServerBootstrap创建

ServerBootstrap 为 netty 建立服务端的辅助类, 以 NIO为例,创建代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) throws Exception {
        ServerBootstrap bs = new ServerBootstrap();
        bs.group(new NioEventLoopGroup(1), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline()
                        .addLast(new HttpServerCodec())
                        .addLast(new HttpObjectAggregator(65535))
                        .addLast(new Controller());
                    }
                }).bind(8080).sync().channel().closeFuture().sync();
    }

核心参数

?
1
2
3
4
//配置属性,如 SO_KEEPALIVE 等private final ServerBootstrapConfig config = new ServerBootstrapConfig(this);
    //acceot 的 子channel所绑定的 事件循环组"
    private volatile EventLoopGroup childGroup;
    private volatile ChannelHandler childHandler;

初始化流程

主要为 绑定本地端口 -> 注册自身到 EventLoop , 并注册 accept 和 read 事件 -> EventLoop的主循环中会不断的select注册的channel的事件,并处理。

首先执行绑定

核心逻辑位于 

io.netty.bootstrap.AbstractBootstrap.doBind(SocketAddress) 和  io.netty.bootstrap.AbstractBootstrap.initAndRegister()中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private ChannelFuture doBind(final SocketAddress localAddress) {
        final ChannelFuture regFuture = initAndRegister();
        ..........if (regFuture.isDone()) {
            // At this point we know that the registration was complete and successful.
            ChannelPromise promise = channel.newPromise();
            //绑定逻辑
            doBind0(regFuture, channel, localAddress, promise);
            return promise;
        } else {
            // Registration future is almost always fulfilled already, but just in case it's not.
            final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
            regFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
                        // IllegalStateException once we try to access the EventLoop of the Channel.
                        promise.setFailure(cause);
                    } else {
                        // Registration was successful, so set the correct executor to use.
                        // See https://github.com/netty/netty/issues/2586
                        promise.registered();
 
                        doBind0(regFuture, channel, localAddress, promise);
                    }
                }
            });
            return promise;
        }
    }

注册自身到 EventLoop

先来看 initAndRegister , 核心逻辑就是利用channelFactory初始化一个NioServerSocketChannel实例,并为其设置上config中的参数,然后将其注册到EventLoop中,实际上是委托的channel的Unsafe来实现注册的,核心逻辑位于 AbstractUnsafe.register0 中 完成注册

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
final ChannelFuture initAndRegister() {
        Channel channel = null;
        try {
            //本例子中实际调用的是  NioServerSocketChannel的构造参数, 并为其设置感兴趣的事件类型为  OP_ACCEPT
            channel = channelFactory.newChannel();
            init(channel);
        } catch (Throwable t) {
            if (channel != null) {
                // channel can be null if newChannel crashed (eg SocketException("too many open files"))
                channel.unsafe().closeForcibly();
            }
            // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
            return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
        }
        ChannelFuture regFuture = config().group().register(channel);
        if (regFuture.cause() != null) {
            if (channel.isRegistered()) {
                channel.close();
            } else {
                channel.unsafe().closeForcibly();
            }
        }
 
         return regFuture;
    }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void init(Channel channel) throws Exception {
        //设置属性
         ..........
 
        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);
                }
                ch.eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        //为NioServerSocketChannel 设置一个 默认的 channelhandler : ServerBootstrapAcceptor , 当发生 accept事件时,将 accept的channel注册到 childEventLoop中
                        pipeline.addLast(new ServerBootstrapAcceptor(
                                ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });
    }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
                //执行channel到 eventloop的 selector
                doRegister();
                neverRegistered = false;
                registered = true;
 
                // 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);
?
1
2
//触发 InboundChannelHnader.channelRegistered 事件
                  pipeline.fireChannelRegistered();
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 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) {
                        //触发channelActive事件,并会为 channel 绑定上 read 事件
                        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);
            }
        }

绑定端口逻辑

initAndRegister注册成功后,开始执行真正的绑定端口逻辑,核心逻辑位于 NioSocketChannel.doBind0(SocketAddress) 中

?
1
2
3
4
5
6
7
private void doBind0(SocketAddress localAddress) throws Exception {
        if (PlatformDependent.javaVersion() >= 7) {
            SocketUtils.bind(javaChannel(), localAddress);
        } else {
            SocketUtils.bind(javaChannel().socket(), localAddress);
        }
    }

至此 绑定个成功, 当触发 ACCEPT 事件时, 会触发  NioServerSocketChannel.doReadMessages -> ServerBootstrapAcceptor.channelRead , 并将 子channel 注册到 childEventLoop中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 {
                //注册channel
                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);
            }
        }

以上就是netty服务端辅助类ServerBootstrap创建逻辑分析的详细内容,更多关于netty辅助类ServerBootstrap创建逻辑的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/ironroot/p/8581065.html

延伸 · 阅读

精彩推荐
  • Java教程Java将时间按月份分段的实现思路与方法

    Java将时间按月份分段的实现思路与方法

    这篇文章主要给大家介绍了关于Java将时间按月份分段的实现思路与方法,通过文中介绍的方法可以将时间分成我们想要的时间段,文中给出了详细的实例代码...

    四级7972021-09-29
  • Java教程Jmeter跨线程组传值调用实现图解

    Jmeter跨线程组传值调用实现图解

    这篇文章主要介绍了Jmeter跨线程组传值调用实现图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以...

    测试逍遥子2992020-07-04
  • Java教程浅谈Java的SPI技术

    浅谈Java的SPI技术

    这篇文章主要介绍了Java的SPI技术的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    思思博士3702020-07-19
  • Java教程JDK1.8新特性Stream流式操作的具体使用

    JDK1.8新特性Stream流式操作的具体使用

    这篇文章主要介绍了JDK1.8新特性Stream流式操作的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋...

    Thinkingcao3862020-09-23
  • Java教程Java之线程编程的4种方法实现案例讲解

    Java之线程编程的4种方法实现案例讲解

    这篇文章主要介绍了Java之线程编程的4种方法实现案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考...

    一只可爱的小狐狸4562021-11-01
  • Java教程spring cloud gateway集成hystrix全局断路器操作

    spring cloud gateway集成hystrix全局断路器操作

    这篇文章主要介绍了spring cloud gateway集成hystrix全局断路器操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    草宝虫11042021-10-14
  • Java教程浅谈在eclipse中如何修改svn的用户名和密码

    浅谈在eclipse中如何修改svn的用户名和密码

    这篇文章主要介绍了在eclipse中如何修改svn的用户名和密码的方法,在eclipse中经常用svn进行代码版本控制,提交或更新代码的时候需要我们输入用户名和密...

    yuanyi8608292542020-07-15
  • Java教程Java Swing实现记事本页面

    Java Swing实现记事本页面

    这篇文章主要为大家详细介绍了Java Swing实现记事本页面,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    大菜彩6322022-07-31