【Netty】Netty之Bootstrapping

简介: 前面已经学习了Netty的EventLoop以及线程模型,接着学习Netty的Bootstrapping。

一、前言


  前面已经学习了Netty的EventLoop以及线程模型,接着学习Netty的Bootstrapping。


二、Bootstrapping

  在学习了Netty中的很多组件后,如何将这些组件有效的组合至应用程序中,这需要使用应用引导程序,引导应用程序是将其配置为运行的过程,Netty以一种绝对应用程序的方式处理引导。

  2.1 Bootstrap类

  Bootstrap类的继承结构图如下图所示。

  50.png

  一个服务器使用一个父通道来接受来自客户端的连接并创建子通道来与它们进行通信,而一个客户端很可能只需要一个非父通道来进行所有的网络交互,而前面讨论的组件会参与引导过程,有些在客户端和服务端都会被使用。两个应用程序类型共同的引导步骤由AbstractBootstrap处理,而特定于客户端或服务器的引导步骤分别由Bootstrap或ServerBootstrap处理。

  为何Bootstrap为Cloneable?因为有时需要创建具有类似或相同设置的多个通道,为了支持此模式,不需要为每个通道创建和配置新的引导实例,因此将AbstractBootstrap标记为Cloneable,在已配置的引导程序上调用clone()方法将返回可立即使用的另一个引导实例,这只会创建引导程序的EventLoopGroup的浅层副本,所以其被所有克隆的通道共享。

  2.2 引导客户端和无连接协议

  Bootstrap在客户端或无连接协议的应用程序中使用。

  1. 引导客户端

  Bootstrap类负责为客户端和使用无连接协议的应用程序创建通道,如下图所示。

  51.png

  以下代码引导使用NIO TCP传输的客户端。  

EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
    .channel(NioSocketChannel.class)
    .handler(new SimpleChannelInboundHandler<ByteBuf>() {
        @Override
        protected void channeRead0(
            ChannelHandlerContext channelHandlerContext,
            ByteBuf byteBuf) throws Exception {
                System.out.println("Received data");
            }
        } );
ChannelFuture future = bootstrap.connect(
    new InetSocketAddress("www.manning.com", 80));
future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture channelFuture)
        throws Exception {
        if (channelFuture.isSuccess()) {
            System.out.println("Connection established");
        } else {
            System.err.println("Connection attempt failed");
            channelFuture.cause().printStackTrace();
        }
    }
} );

 2. Channel和EventLoopGroup兼容性

  io.netty.channel包中的类结构如下。

   52.png533.png

  可以看到对于NIO和OIO传输,都有相关的EventLoopGroup和Channel实现,不能混合具有不同前缀的组件,例如NioEventLoopGroup和OioSocketChannel。如下代码展示不兼容的使用用法。

EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
    .channel(OioSocketChannel.class)
    .handler(new SimpleChannelInboundHandler<ByteBuf>() {
        @Override
        protected void channelRead0(
            ChannelHandlerContext channelHandlerContext,
            ByteBuf byteBuf) throws Exception {
                System.out.println("Received data");
            }
    } );
ChannelFuture future = bootstrap.connect(
    new InetSocketAddress("www.manning.com", 80));
future.syncUninterruptibly();

 其中NIOEventLooop和OioSocketChannel不兼容,将会抛出IllegalStateException异常。

  在调用bind或者connect方法之前,需要调用group、channel或channelFactory、handler方法,否则会抛出IllegalStateException异常。

  2.3 引导服务器

  ServerChannel的实现负责创建接受连接的子通道,ServerBootstrap通过bind()方法创建一个ServerChannel,ServerChannel可管理多个子通道,具体如下图所示。

  55.png

  下面代码展示了如何引导服务器。  

NioEventLoopGroup group = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(group)
    .channel(NioServerSocketChannel.class)
    .childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx,
            ByteBuf byteBuf) throws Exception {
                System.out.println("Received data");
            }
    } );
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture channelFuture)
        throws Exception {
        if (channelFuture.isSuccess()) {
            System.out.println("Server bound");
        } else {
            System.err.println("Bound attempt failed");
            channelFuture.cause().printStackTrace();
        }
    }
} );

 2.4 由通道引导客户端

  假设服务器正在处理客户端请求,并要求服务器作为第三个系统的客户端,如代理服务器。此时需要从ServerChannel引导客户端通道。一个较好的方法是通过Bootstrap类的group方法传递Channel对应的EventLoop,因为所有分配给EventLoop的通道都使用相同的线程,这避免了额外的线程创建和相关的上下文切换。具体如下图所示。

  56.png

  通过group方法共享EventLoop的代码如下。 

ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())
    .channel(NioServerSocketChannel.class)
    .childHandler(
        new SimpleChannelInboundHandler<ByteBuf>() {
            ChannelFuture connectFuture;
            @Override
            public void channelActive(ChannelHandlerContext ctx)
                throws Exception {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.channel(NioSocketChannel.class).handler(
                    new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(
                        ChannelHandlerContext ctx, ByteBuf in)
                        throws Exception {
                        System.out.println("Received data");
                    }
                } );
            bootstrap.group(ctx.channel().eventLoop());
            connectFuture = bootstrap.connect(
                new InetSocketAddress("www.manning.com", 80));
        }
        @Override
        protected void channelRead0(
            ChannelHandlerContext channelHandlerContext,
                ByteBuf byteBuf) throws Exception {
            if (connectFuture.isDone()) {
                // do something with the data
            }
        }
    } );
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
future.addListener(new ChannelFutureListener() {
    @Override
        public void operationComplete(ChannelFuture channelFuture)
        throws Exception {
        if (channelFuture.isSuccess()) {
            System.out.println("Server bound");
        } else {
            System.err.println("Bind attempt failed");
            channelFuture.cause().printStackTrace();
        }
    }
} );

2.5 在引导过程中添加多个ChannelHandler

  在上面示例中,在引导过程中通过调用handler或者childHandler方法添加单个ChannelHandler,并且我们知道在ChannelPipeline中可以有多个ChannelHandler链,但是在引导过程中只添加了一个ChannelHandler。Netty提供了ChannelInboundHandlerAdapter,其提供了initChannel方法,该方法可以将多个ChannelHandler添加至ChannelPipeline中,你只需要将ChannelInitializer的实现提供给引导程序,而一旦Channel注册了EventLoop,那么initChannel方法将被调用,当方法返回后,ChannelInitializer将自身从ChannelPipeline中移除,如下代码展示了具体的操作。 

ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializerImpl());
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
future.sync();
final class ChannelInitializerImpl extends ChannelInitializer<Channel> {
    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpClientCodec());
        pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
    }
}

     2.6 使用Netty的ChannelOptions和attributes

  当创建通道时手动配置非常麻烦,可以使用option方法将ChannelOptions提供给引导程序,你提供的值将自动应用于在引导中创建的所有通道。ChannelOptions包括连接详细信息,如保持活动、超时属性和缓冲区设置等。Netty还可使用AttributeKey抽象类来配置属性值,如下代码展示了具体使用。

final AttributeKey<Integer> id = new AttributeKey<Integer>("ID");
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(
    new SimpleChannelInboundHandler<ByteBuf>() {
        @Override
        public void channelRegistered(ChannelHandlerContext ctx)
            throws Exception {
            Integer idValue = ctx.channel().attr(id).get();
            // do something with the idValue
        @Override
        protected void channelRead0(
            ChannelHandlerContext channelHandlerContext,
            ByteBuf byteBuf) throws Exception {
            System.out.println("Received data");
        }
    }
);
bootstrap.option(ChannelOption.SO_KEEPALIVE,true)
    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
bootstrap.attr(id, 123456);
ChannelFuture future = bootstrap.connect(
new InetSocketAddress("www.manning.com", 80));
future.syncUninterruptibly();


 2.7 引导DatagramChannels

  前面的示例使用的SocketChannel,是基于TCP协议,但是Bootstrap也可以用于无连接的协议,如UDP协议,唯一的区别在于不调用connect方法,只使用bind方法,具体如下代码所示。 

Bootstrap bootstrap = new Bootstrap();
bootstrap.group(new OioEventLoopGroup()).channel(
    OioDatagramChannel.class).handler(
    new SimpleChannelInboundHandler<DatagramPacket>(){
        @Override
        public void channelRead0(ChannelHandlerContext ctx,
            DatagramPacket msg) throws Exception {
            // Do something with the packet
        }
    }
);
ChannelFuture future = bootstrap.bind(new InetSocketAddress(0));
future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture channelFuture)
        throws Exception {
        if (channelFuture.isSuccess()) {
            System.out.println("Channel bound");
        } else {
            System.err.println("Bind attempt failed");
            channelFuture.cause().printStackTrace();
        }
    }
})

 2.8 关闭

  引导使得应用运行,但是之后需要优雅的关闭引导。需要关闭EventLoopGroup,可调用EventLoopGroup.shutdownGracefully() 方法,其是异步的,会返回ChannelFuture,在观泉关闭后会收到通知,下面是使用示例。  

EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
    .channel(NioSocketChannel.class);
...
Future<?> future = group.shutdownGracefully();
// block until the group has shutdown
future.syncUninterruptibly();

也可以在调用shutdownGracefully方法之前显示调用close方法,要让EventLoopGroup自己主动关闭。


三、总结


  本篇博文讲解了Bootstrap,包括客户端和服务端的引导,以及如何启动标准的客户端和服务端程序。也谢谢各位园友的观看~


  

目录
相关文章
|
JavaScript
JS设置日期为0时0分0秒
项目中经常要给设置默认值,搜索从哪天开始,这时候,如果直接通过new Date()来获取时间,会有时分秒,如果快速设置为0时0分0秒?
866 0
|
安全 编译器 C++
Microsoft Visual C++ Redistributable的作用主要体现以及可以删除吗?
这些是Microsoft Visual C++不同版本的Redistributable安装包,用于32位系统,确保相关应用正常运行。它们提供C++运行时环境,简化部署流程,支持第三方库及框架,并确保应用兼容性。定期更新可修复问题并引入新功能。在空间有限或需解决程序冲突时可考虑删除,但需谨慎操作以防影响应用稳定性和兼容性。删除前请确认无应用依赖,并通过控制面板安全卸载。
4468 1
Microsoft Visual C++ Redistributable的作用主要体现以及可以删除吗?
|
开发者
鸿蒙next版开发:ArkTS组件通用属性(图形变换)
在HarmonyOS 5.0中,ArkTS提供了强大的图形变换功能,支持组件的旋转、缩放和平移操作,增强用户界面的视觉效果和交互体验。本文详细解读了ArkTS中图形变换的通用属性,并提供了示例代码,包括基础变换、组合变换和动画效果的应用。通过这些示例,开发者可以轻松实现复杂的视觉效果和动态用户界面。
1127 1
|
人工智能 监控 智能硬件
OKR的实施
OKR的实施
1276 7
|
Java API 数据处理
Java 包(package)的作用详解
在 Java 中,包(package)用于组织和管理类与接口,具有多项关键作用:1)系统化组织代码,便于理解和维护;2)提供命名空间,避免类名冲突;3)支持访问控制,如 public、protected、默认和 private,增强封装性;4)提升代码可维护性,实现模块化开发;5)简化导入机制,使代码更简洁;6)促进模块化编程,提高代码重用率;7)管理第三方库,避免命名冲突;8)支持 API 设计,便于功能调用;9)配合自动化构建工具,优化项目管理;10)促进团队协作,明确模块归属。合理运用包能显著提升代码质量和开发效率。
1809 4
|
前端开发 JavaScript API
React、Vue.js 和 Angular前端三大框架对比与选择
前端框架是用于构建用户界面的工具和库,它提供组件化结构、数据绑定、路由管理和状态管理等功能,帮助开发者高效地创建和维护 web 应用的前端部分。常见的前端框架如 React、Vue.js 和 Angular,能够提高开发效率并促进团队协作。
2103 4
|
人工智能 运维 监控
智研未来,直击 AI DevOps,阿里云用户交流日杭州站来啦!
在这个技术日新月异的时代,云上智能化DevOps正以前所未有的速度推动企业创新边界,重塑软件开发的效率与品质。 为深入探索这一变革之路,我们诚邀您参与我们的专属闭门技术沙龙,携手开启一场关于云上智能化DevOps的挑战、实践与未来的展望之旅。
8093 0
智研未来,直击 AI DevOps,阿里云用户交流日杭州站来啦!
|
安全 Linux 文件存储
在Linux中,服务器开不了机怎么解决⼀步步的排查?
在Linux中,服务器开不了机怎么解决⼀步步的排查?
|
虚拟化
网工,第一次在服务器上安装AD域服务
网工,第一次在服务器上安装AD域服务
819 1
|
数据安全/隐私保护 Python
如何使用Python自动发送邮件?
如何使用Python自动发送邮件?
816 1