BootStrap在netty的應用程序中負責引導服務器和客戶端。netty包含了兩種不一樣類型的引導:
1. 使用服務器的ServerBootStrap,用於接受客戶端的鏈接以及爲已接受的鏈接建立子通道。
2. 用於客戶端的BootStrap,不接受新的鏈接,而且是在父通道類完成一些操做。html
通常服務端的代碼以下所示:java
SimpleServer.javabootstrap
/** * Created by chenhao on 2019/9/4. */ public final class SimpleServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new SimpleServerHandler()) .childHandler(new SimpleServerInitializer()) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(8888).sync(); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
SimpleServerHandler.java數組
private static class SimpleServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("channelActive"); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { System.out.println("channelRegistered"); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { System.out.println("handlerAdded"); } }
SimpleServerInitializer.java服務器
public class SimpleServerInitializer extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); pipeline.addLast("handler", new SimpleChatServerHandler()); System.out.println("SimpleChatClient:" + ch.remoteAddress()+"鏈接上"); } }
在上篇博文(Netty源碼分析 (一)----- NioEventLoopGroup)中 剖析了以下的兩行代碼內部的構造函數中幹了些什麼。ide
EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup();
具體能夠見上篇博文,對於如上的兩行代碼獲得的結論是:函數
1、 若是不指定線程數,則線程數爲:CPU的核數*2oop
2、根據線程個數是否爲2的冪次方,採用不一樣策略初始化chooser源碼分析
3、產生nThreads個NioEventLoop對象保存在children數組中。post
能夠理解NioEventLoop就是一個線程,線程NioEventLoop中裏面有以下幾個屬性:
一、NioEventLoopGroup (在父類SingleThreadEventExecutor中)
二、selector
三、provider
四、thread (在父類SingleThreadEventExecutor中)
更通俗點就是: NioEventLoopGroup就是一個線程池,NioEventLoop就是一個線程。NioEventLoopGroup線程池中有N個NioEventLoop線程。
本篇博文將分析以下幾行代碼裏面作了些什麼。
ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new SimpleServerHandler()) .childHandler(new SimpleServerInitializer()) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true);
ServerBootstrap類的繼承結構以下:
該類的參數,有必要列出:
private final Map<ChannelOption<?>, Object> childOptions = new LinkedHashMap<ChannelOption<?>, Object>(); private final Map<AttributeKey<?>, Object> childAttrs = new LinkedHashMap<AttributeKey<?>, Object>(); private volatile EventLoopGroup childGroup; private volatile ChannelHandler childHandler;
其父類AbstractBootstrap的參數
private volatile EventLoopGroup group; private volatile ChannelFactory<? extends C> channelFactory; private volatile SocketAddress localAddress; private final Map<ChannelOption<?>, Object> options = new LinkedHashMap<ChannelOption<?>, Object>(); private final Map<AttributeKey<?>, Object> attrs = new LinkedHashMap<AttributeKey<?>, Object>(); private volatile ChannelHandler handler;
下面主要看下這個鏈式設置相關的參數。
public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) { super.group(parentGroup); if (childGroup == null) { throw new NullPointerException("childGroup"); } if (this.childGroup != null) { throw new IllegalStateException("childGroup set already"); } this.childGroup = childGroup; return this; }
即將workerGroup保存在 ServerBootstrap對象的childGroup屬性上。 bossGroup保存在ServerBootstrap對象的group屬性上
public B channel(Class<? extends C> channelClass) { if (channelClass == null) { throw new NullPointerException("channelClass"); } return channelFactory(new BootstrapChannelFactory<C>(channelClass)); } public B channelFactory(ChannelFactory<? extends C> channelFactory) { if (channelFactory == null) { throw new NullPointerException("channelFactory"); } if (this.channelFactory != null) { throw new IllegalStateException("channelFactory set already"); } this.channelFactory = channelFactory; return (B) this; }
函數功能:設置父類屬性channelFactory 爲: BootstrapChannelFactory類的對象。其中這裏BootstrapChannelFactory對象中包括一個clazz屬性爲:NioServerSocketChannel.class,從以下該類的構造函數中能夠明顯的獲得這一點。
private static final class BootstrapChannelFactory<T extends Channel> implements ChannelFactory<T> { private final Class<? extends T> clazz; BootstrapChannelFactory(Class<? extends T> clazz) { this.clazz = clazz; } @Override public T newChannel() { try { return clazz.newInstance(); } catch (Throwable t) { throw new ChannelException("Unable to create Channel from class " + clazz, t); } } @Override public String toString() { return StringUtil.simpleClassName(clazz) + ".class"; } }
而且BootstrapChannelFactory中提供 newChannel()方法,咱們能夠看到 clazz.newInstance(),主要是經過反射來實例化NioServerSocketChannel.class
public B handler(ChannelHandler handler) { if (handler == null) { throw new NullPointerException("handler"); } this.handler = handler; return (B) this; }
注意:這裏的handler函數的入參類是咱們本身提供的。以下,後面的博文中將會分析這個handler將會在哪裏以及什麼時候被調用,這裏只須要記住這一點便可
private static class SimpleServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("channelActive"); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { System.out.println("channelRegistered"); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { System.out.println("handlerAdded"); } }
public ServerBootstrap childHandler(ChannelHandler childHandler) { if (childHandler == null) { throw new NullPointerException("childHandler"); } this.childHandler = childHandler; return this; }
由最後一句可知,其實就是講傳入的childHandler賦值給ServerBootstrap的childHandler屬性。
該函數的主要做用是設置channelHandler來處理客戶端的請求的channel的IO。 這裏咱們通常都用ChannelInitializer這個類的實例或則繼承自這個類的實例
這裏我是經過新建類SimpleChatServerInitializer繼承自ChannelInitializer。具體的代碼以下:
public class SimpleChatServerInitializer extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); pipeline.addLast("handler", new SimpleChatServerHandler()); System.out.println("SimpleChatClient:" + ch.remoteAddress()+"鏈接上"); } }
咱們再看看ChannelInitializer這個類的繼承圖可知ChannelInitializer其實就是繼承自ChannelHandler的
可知,這個類其實就是往pipeline中添加了不少的channelHandler。
這裏調用的是父類的AbstractBootstrap的option()方法,源碼以下:
public <T> B option(ChannelOption<T> option, T value) { if (option == null) { throw new NullPointerException("option"); } if (value == null) { synchronized (options) { options.remove(option); } } else { synchronized (options) { options.put(option, value); } } return (B) this; }
其中最重要的一行代碼就是:
options.put(option, value);
這裏用到了options這個參數,在AbstractBootstrap的定義以下:
private final Map<ChannelOption<?>, Object> options = new LinkedHashMap<ChannelOption<?>, Object>();
可知是私有變量,並且是一個Map集合。這個變量主要是設置TCP鏈接中的一些可選項,並且這些屬性是做用於每個鏈接到服務器被建立的channel。
這裏調用的是父類的ServerBootstrap的childOption()方法,源碼以下:
public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value) { if (childOption == null) { throw new NullPointerException("childOption"); } if (value == null) { synchronized (childOptions) { childOptions.remove(childOption); } } else { synchronized (childOptions) { childOptions.put(childOption, value); } } return this; }
這個函數功能與option()函數幾乎同樣,惟一的區別是該屬性設定只做用於被acceptor(也就是boss EventLoopGroup)接收以後的channel。
比較簡單哈,主要是將咱們提供的參數設置到其相應的對象屬性中去了。 由於後面會用到以下的幾個屬性,所以最好知道下,這些屬性是什麼時候以及在那裏賦值的。
一、group:workerGroup保存在 ServerBootstrap對象的childGroup屬性上。 bossGroup保存在ServerBootstrap對象的group屬性上
二、channelFactory:BootstrapChannelFactory類的對象(clazz屬性爲:NioServerSocketChannel.class)
三、handler:SimpleServerHandler
四、childHandler
五、option
六、childOption