傻大方提要:【绝!真就一文全懂!Netty线程模型+启动详细分析+内存管理( 三 )】服务端启动分析以创建一个Netty服务端为例 public class NettyServer {public void bind(int port){// 创建EventLoopGroupEventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup w...
按关键词阅读:
服务端启动分析以创建一个Netty服务端为例
public class NettyServer {public void bind(int port){// 创建EventLoopGroupEventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {// 创建ServerBootStrap实例// ServerBootstrap 用于启动NIO服务端的辅助启动类 , 目的是降低服务端的开发复杂度ServerBootstrap b = new ServerBootstrap();// 绑定Reactor线程池b.group(bossGroup, workerGroup)// 设置并绑定服务端Channel// 指定所使用的NIO传输的Channel.channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).handler(new LoggingServerHandler()).childHandler(new ChannelInitializer(){@Overrideprotected void initChannel(Channel ch) throws Exception {ch.pipeline().addLast("decoder", new HttpRequestDecoder());ch.pipeline().addLast("encoder", new HttpResponseEncoder());ch.pipeline().addLast("httpServerHandler", new HttpServerHandler());}});// 绑定端口 , 同步等待成功ChannelFuture future = b.bind(port).sync();// 等待服务端监听端口关闭future.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {// 优雅地关闭bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}
服务端的创建主要步骤为:
- 创建 ServerBootstrap 实例
- 设置并绑定 Reactor 线程池
- 设置服务端 Channel
- 添加并设置 ChannelHandler
- 绑定并启动监听端口
EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();
bossGroup 为 BOSS 线程组 , 用于服务端接受客户端的连接, workerGroup 为 worker 线程组 , 用于进行 SocketChannel 的网络读写 。创建ServerBootstrap实例
ServerBootstrap b = new ServerBootstrap();
ServerBootStrap为Netty服务端的启动引导类 , 用于帮助用户快速配置、启动服务端服务 。客户端的引导类是Bootstrap 。 ServerBootStrap 提供了如下一些方法方法名称 方法描述 group 设置 ServerBootstrap 要用的 EventLoopGroup channel 设置将要被实例化的 ServerChannel 类 option 实例化的 ServerChannel 的配置项 Handler 设置并添加 Handler bind 绑定 ServerChannel
设置并绑定线程池
b.group(bossGroup, workerGroup)
调用group()方法 , 为ServerBootstrap实例设置绑定reactor线程池 public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {super.group(parentGroup);// 绑定boosGroupif (childGroup == null) {throw new NullPointerException("childGroup");}if (this.childGroup != null) {throw new IllegalStateException("childGroup set already");}this.childGroup = childGroup;// 绑定workerGroupreturn this;}
设置服务端Channel.channel(NioServerSocketChannel.class)
调用channel()方法设置服务端Channel类型 , 注意这里参数是Class对象 , Netty通过工厂类 , 利用反射来创建NioServerSocketChannel对象 public B channel(Class extends C> channelClass) {if (channelClass == null) {throw new NullPointerException("channelClass");}return channelFactory(new ReflectiveChannelFactory(channelClass));}
这里传递的是 ReflectiveChannelFactory , 其源代码如下: public class ReflectiveChannelFactory implements ChannelFactory {private final Class extends T> clazz;public ReflectiveChannelFactory(Class extends T> clazz) {if (clazz == null) {throw new NullPointerException("clazz");}this.clazz = clazz;}//需要创建 channel 的时候 , 该方法将被调用@Overridepublic T newChannel() {try {// 反射创建对应 channelreturn clazz.newInstance();} catch (Throwable t) {throw new ChannelException("Unable to create Channel from class " + clazz, t);}}@Overridepublic String toString() {return StringUtil.simpleClassName(clazz) + ".class";}}
添加并设置ChannelHandler.handler(new LoggingServerHandler()) .childHandler(new ChannelInitializer(){@Overrideprotected void initChannel(Channel ch) throws Exception {ch.pipeline().addLast("decoder", new HttpRequestDecoder());ch.pipeline().addLast("encoder", new HttpResponseEncoder());ch.pipeline().addLast("httpServerHandler", new HttpServerHandler());} })
handler()设置的 Handler 是服务端 NioServerSocketChannel的 , childHandler()`设置的 Handler 是属于每一个新建的 NioSocketChannel 的绑定端口 , 启动服务端绑定端口并启动服务 , 如下:
ChannelFuture future = b.bind(port).sync();
深入源码我们发现核心方法有两个initAndRegister() ,doBind0()initAndRegister()
final ChannelFuture initAndRegister() {Channel channel = null;// ...channel = channelFactory.newChannel();//...init(channel);//...ChannelFuture regFuture = config().group().register(channel);//...return regFuture;}
initAndRegister做了3件事:1.new一个Channel

稿源:(未知)
【傻大方】网址:http://www.shadafang.com/c/111J293N2020.html
标题:绝!真就一文全懂!Netty线程模型+启动详细分析+内存管理( 三 )