随笔 - 531  文章 - 0  评论 - 3  阅读 - 10215 

 

采用nio:同步非阻塞的io模型

bio: 处理多个客户端请求时,每个客户端连接需要一个独立的线程来处理 I/O 操作,会大量消耗资源

 

nio组成: buffer ,selector,channel

nio采用selector,监听socket channel 上是否有读写操作的事件,然后才执行读写

 

netty核心组件

  ⚠️eventgroup是一个线程池,每个被创建的线程处理一个channelPipeline(channel), pipeline中有一组串起来的处理器

 

EventLoop(事件循环),是一个包含多个线程的集合

EventLoopGroup(事件循环组)

channel(管道),channelPipeline ( channelHandler)

 

 

工作流程如图

 

 

details:

 

bootstrap,server bootstrap  对应client和server的启动类:

  • ServerBootstrap:
    • 需要两个线程组( boss group 和 worker group , 对应 接收连接和IO处理
    • 监听一个端口
  • Bootstrap
    • 连接server主机和端口

 

channel:

网络接口的抽象,进行io操作,

  NioServerSocketChannel , NioSocketChannel

 

 

EventLoop: (其中包含selector机制)

  如前所述,是一个线程池,  默认构造函数创建 线程数 【 CPU核心数*2】

  监听网络事件,调用处理器进行IO处理

  eventloop和thread是1:1 的, eventloop可以绑定多个channel,通过selector处理io操作

 

 

channelpipeline: 

  是channel的一部分(1 : 1),pipeline中包含多个channelHandler , 呈现一个链表形状,通过 handlercontext管理

 

bootstrap启动

  无论是client还是server,都设置了线程组(nioEventLoop),线程模型(NIO) , channel 处理逻辑

 

 

一些代码 

channelfuture: 异步操作的结果,implements future<T>

 

复制代码
ChannelFuture future = channel.writeAndFlush(message);
future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture f) throws Exception {
        if (f.isSuccess()) {
            System.out.println("Message sent successfully!");
        } else {
            System.err.println("Failed to send message: " + f.cause());
        }
    }
});
复制代码

 

 

大部分网络io框架采用reactor模型【事件驱动,多路复用】

boss-group用来接收连接请求,然后转发到eventgroup

 

netty 采用 NioEventloopgroup线程池 的线程模型

 

server boostrap, client就不贴了类似的

复制代码
 serverBootstrap.group(bossGroup, workerGroup) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // 指定服务端通道类型
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 处理每一个连接的SocketChannel
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加编码器、解码器等处理器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new SimpleServerHandler()); // 自定义处理器
                        }
                    });
                  

            // 绑定端口并启动服务器
            ChannelFuture future = serverBootstrap.bind(port).sync();
复制代码

 

posted on   towboat  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2023-10-04 AT_abc291_f
点击右上角即可分享
微信分享提示