netty服务端启动流程
Demo代码
下面是一个简单的EchoServer
public void start() throws InterruptedException {
final EchoServerChildHandler serverChildHandler=new EchoServerChildHandler();
EventLoopGroup boss=new NioEventLoopGroup(1);
EventLoopGroup worker=new NioEventLoopGroup(3);
try {
ServerBootstrap b=new ServerBootstrap();
b.group(boss,worker)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_RCVBUF, 1024*9)
.localAddress(port)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(serverChildHandler);
}
});
ChannelFuture f=b.bind().sync();
f.channel().closeFuture().sync();
}finally {
boss.shutdownGracefully().sync();
worker.shutdownGracefully().sync();
}
}
总体流程
- 创建bossgroup、workergroup,设置到启动的引导类中
- 设置channel类型为NIO
- 设置端口号,也可以在后面bind方法传入端口号
- 设置一些option参数,连接超时时间,缓冲区大小等参数
- 设置handler处理器,一般设置wokergroup的就够了
- 绑定端口
一、EventLoop的创建
EventLoopGroup boss=new NioEventLoopGroup(1);
这行创建了一个boss的EventLoopGroup,进去看构造函数可以看出,默认Thread线程是cpu核数*2,但是如果只需要绑定一个端口,就把参数设置为1,否则多创建的就没有作用
public NioEventLoopGroup(int nThreads) {
this(nThreads, (Executor) null);
}
public NioEventLoopGroup(int nThreads, Executor executor) {
this(nThreads, executor, SelectorProvider.provider());
}
public NioEventLoopGroup(
int nThreads, Executor executor, final SelectorProvider selectorProvider) {
this(nThreads, executor, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
}
public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
final SelectStrategyFactory selectStrategyFactory) {
super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
}
--------------------------------
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
super(nThreads ==