netty启动过程

netty服务端启动流程Demo代码一、EventLoop的创建二、启动Demo代码下面是一个简单的EchoServer public void start() throws InterruptedException { final EchoServerChildHandler serverChildHandler=new EchoServerChildHandler(); EventLoopGroup boss=new NioEventLoo
摘要由CSDN通过智能技术生成

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();
        }
    }

总体流程

  1. 创建bossgroup、workergroup,设置到启动的引导类中
  2. 设置channel类型为NIO
  3. 设置端口号,也可以在后面bind方法传入端口号
  4. 设置一些option参数,连接超时时间,缓冲区大小等参数
  5. 设置handler处理器,一般设置wokergroup的就够了
  6. 绑定端口

一、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 == 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值