当前位置: 首页 > news >正文

Netty源码剖析之NIOEventLoopGroup创建流程

准备

1、NettyServer

public class NettyServer {

    public static void main(String[] args) throws InterruptedException {

        // 1、创建bossGroup线程组:处理网络连接事件。默认线程数:2*处理器线程数
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 2、创建workGroup线程组:处理网络read/write事件。 默认线程数:2*处理器线程数
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        // 3、创建服务端启动助手
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 4、服务端启动助手,设置线程组
        serverBootstrap.group(bossGroup,workerGroup)
                // 5、设置服务端Channel实现类
                .channel(NioServerSocketChannel.class)
                // 6、设置bossGroup线程队列中等待连接个数
                .option(ChannelOption.SO_BACKLOG,128)
                // 7、设置workerGroup中线程活跃状态
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                // 使用channelInitializer 可以配置多个handler
                .childHandler(new ChannelInitializer<SocketChannel>() {// 8、设置一个通道初始化对象
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 9、向pipeline中添加自定义的channelHandler, 处理socketChannel传送的数据
                        ch.pipeline().addLast(new NettyServerHandler());
                    }
                });

        // 10、服务端启动并绑定端口
        ChannelFuture future = serverBootstrap.bind(9999).sync();
        // 给服务器启动绑定结果,对结果进行监听,触发回调
        future.addListener((ChannelFuture channelFuture)-> {
            if(channelFuture.isSuccess()){
                System.out.println("服务器启动成功");
            }else {
                System.out.println("服务器启动失败");
            }
        });


        // 11、关闭监听通道和连接池,将异步改同步
        future.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

2、NettyServerHandler

/**
 * 自定义的channelHandler处理器
 *
 * 事件触发,触发相应函数
 */
public class NettyServerHandler implements ChannelInboundHandler {

    /**
     * 通道读取事件
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuffer = (ByteBuf)msg;
        System.out.println("客户端:"+byteBuffer.toString(CharsetUtil.UTF_8));
    }

    /**
     * 通道数据读取完毕事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        TimeUnit.SECONDS.sleep(2);
        ctx.writeAndFlush(Unpooled.copiedBuffer("叫我靓仔!!!".getBytes()));
    }

    /**
     * 发生异常捕获事件
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 通道就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    }
}

3、NettyClient

/**
 * nettyClient
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        // 1、创建线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 2、创建客户端启动助手bootstrap
        Bootstrap bootstrap = new Bootstrap();
        // 3、配置线程组
        bootstrap.group(group)
                // 4、定义socketChannel的实现类
                .channel(NioSocketChannel.class)
                // 5、定义channelHandler, 处理socketChannel的数据
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //6、向pipeline中添加自定义业务处理handler
                        ch.pipeline().addLast(new NettyClientHandler());
                    }
                });

        // 7、启动客户端, 等待连接服务端, 同时将异步改为同步
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(9999)).sync();
        // 8、关闭通道和关闭连接池
        future.channel().closeFuture().sync();
        group.shutdownGracefully();


    }
}

4、NettyClientHandler

/**
 * 自定义的channelHandler处理器
 * <p>
 * 事件触发,触发相应函数
 */
public class NettyClientHandler implements ChannelInboundHandler {

    /**
     * 通道读取事件
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("服务端:" +
                byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 通道数据读取完毕事件
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("不行,不行啊!!!".getBytes()));
    }

    /**
     * 发生异常捕获事件
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 通道就绪事件
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("你好哇 小客客!!!".getBytes()));
    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    }
}

NioEventLoopGroup创建流程

1、定义线程数
在这里插入图片描述
在这里插入图片描述
如果创建线程组的时候没有指定线程数,那么默认线程数将通过指定系统参数或者CPU逻辑处理核数*2来定义。Math.max(1, SystemPropertyUtil.getInt( "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

2、获取执行器

在这里插入图片描述
在这里插入图片描述
ThreadPerTaskExecutor本质上就要线程工厂创建新的线程执行任务,这里包装了一层。
在这里插入图片描述
Thread 使用的是FastThreadLocalThread,优化ThreadLocal在哪?

3、创建n个线程的NioEventLoop
在这里插入图片描述

在这里插入图片描述

3.1、创建任务队列TaskQueue
在这里插入图片描述
3.2、获取SelectorProvider提供器

在这里插入图片描述
selectNow 以非阻塞的方式获取感兴趣的事件,感兴趣事件指:SocketChannel注册到Selector上要求监听的事件

3.3、绑定SelectStrategy
在这里插入图片描述
SelectStrategy 实现类为 DefaultSelectStrategy,执行逻辑,判断任务队列中是否有任务,最终返回一个int值,返回SELECT = -1 为阻塞当前线程

4、为每个NioEventLoop绑定一个中断监听器
在这里插入图片描述

总结

NioEventLoopGroup内部结构
在这里插入图片描述
在这里插入图片描述

执行图

在这里插入图片描述

相关文章:

  • Python语言学习:Python语言学习之面向对象编程OO(继承封装多态)/类方法/装饰器的简介、案例应用之详细攻略
  • 计算机毕业设计ssm基于java网上心理咨询系统50fxl系统+程序+源码+lw+远程部署
  • 备战数学建模47-数模常规算法之图论(攻坚站12)
  • 算法学习十八补二叉树递归套路+贪心算法一
  • Linux常用命令(上).
  • 叠氮聚乙二醇生物素 N3-PEG-Biotin Azide-PEG-Biotin的结构式
  • Java网络编程1
  • Opencv项目实战:09 物体尺寸测量
  • 记一次vue前端导出excel
  • 缓存预热Springboot定时任务
  • 基于遗传算法的BP神经网络在汇率预测中的应用研究(Matlab代码实现)
  • vue3+three.js实现疫情可视化
  • UNIAPP day_05(9.3) Cookie、WebStorage、Session 和 Token的区别、uni-app最终部署
  • 1、代理模式
  • python-json校验-jsonpath
  • 【从零开始安装kubernetes-1.7.3】2.flannel、docker以及Harbor的配置以及作用
  • Android交互
  • C++11: atomic 头文件
  • Druid 在有赞的实践
  • express如何解决request entity too large问题
  • extract-text-webpack-plugin用法
  • Flex布局到底解决了什么问题
  • Java 实战开发之spring、logback配置及chrome开发神器(六)
  • Promise初体验
  • SQLServer之创建显式事务
  • Sublime text 3 3103 注册码
  • 半理解系列--Promise的进化史
  • 工作手记之html2canvas使用概述
  • 码农张的Bug人生 - 见面之礼
  • 批量截取pdf文件
  • 阿里云移动端播放器高级功能介绍
  • 好程序员web前端教程分享CSS不同元素margin的计算 ...
  • (2)nginx 安装、启停
  • (接口自动化)Python3操作MySQL数据库
  • (一)基于IDEA的JAVA基础1
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • .NET Core MongoDB数据仓储和工作单元模式封装
  • .NET Core使用NPOI导出复杂,美观的Excel详解
  • .net 打包工具_pyinstaller打包的exe太大?你需要站在巨人的肩膀上-VC++才是王道
  • .NET简谈设计模式之(单件模式)
  • .net使用excel的cells对象没有value方法——学习.net的Excel工作表问题
  • .Net下使用 Geb.Video.FFMPEG 操作视频文件
  • /usr/bin/env: node: No such file or directory
  • [ linux ] linux 命令英文全称及解释
  • [C# 网络编程系列]专题六:UDP编程
  • [C#]C# OpenVINO部署yolov8图像分类模型
  • [C++]:for循环for(int num : nums)
  • [Effective C++读书笔记]0012_复制对象时勿忘其每一部分
  • [MAC OS] 常用工具
  • [macOS] Mojave10.14 夜神安卓模拟器启动问题
  • [one_demo_1]php中的文件锁
  • [OpenCV学习笔记]获取鼠标处图像的坐标和像素值
  • [Ruby on Rails系列]4、专题:Rails应用的国际化[i18n]
  • [Thinking]三个行
  • [VS] 诊断工具,检测内存泄漏,进行内存调优