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

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

 

nio组成: buffer ,selector,channel

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

 

netty核心组件

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

 

bytebuf:网络传输使用的字节容器

channel(管道),channelPipeline

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

EventLoopGroup(事件循环组)

 

工作流程如图

 

details:

 

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

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

 

channel:

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

  NioServerSocketChannel , NioSocketChannel

 

 

EventLoop:

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

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

  可以绑定多个channel,每个channel一个thread处理

 

 

channelpipeline: 

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

 

 

 

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 2024-10-04 14:32  towboat  阅读(0)  评论(0编辑  收藏  举报