Netty彻底入门

Netty介绍

  • NIO的类库和API复杂,需要熟练掌握Selector、ServerSocketChannel、SocketChannel,ByteBuffer等;导致开发工作量和难度都非常大;例如:断线重连、网络闪断、心跳处理,网络阻塞、异常处理等;
  • Netty对JDK自带的NIO的API进行了良好的封装,解决了上述问题。且Netty具有高性能、吞吐量、低延迟;

Netty使用场景

  • 互联网行业:Dubbo的RPC框架使用Dubbo协议进行节点通信,Dubbo协议默认使用Netty作为基础通讯组件
  • 游戏行业: Netty作为高性能的基础通信组件,它本身提供了 TCP/UDP 和 HTTP 协议栈。
  • 大数据领域:经典的 Hadoop 的高性能通信和序列化组件 Avro 的 RPC 框架,默认采用 Netty 进行跨界点通信,它的 Netty Service 基于 Netty 框架二次封装实现

Netty线程模型

如图所示:
在这里插入图片描述

  • Netty 抽象出两组线程池BossGroup和WorkerGroup,BossGroup专门负责接收客户端的连接, WorkerGroup专门负责网络的读写
  • BossGroup和WorkerGroup类型都是NioEventLoopGroup
  • NioEventLoopGroup 相当于一个事件循环线程组, 这个组中含有多个事件循环线程 , 每一个事件 循环线程是NioEventLoop
  • 每个NioEventLoop都有一个selector , 用于监听注册在其上的socketChannel的网络通讯
  • 每个Boss NioEventLoop线程内部循环执行的步骤有 3 步
    1)处理accept事件 , 与client 建立连接 , 生成 NioSocketChannel
    2)将NioSocketChannel注册到某个worker NIOEventLoop上的selector
    3)处理任务队列的任务 , 即runAllTasks
  • 每个worker NIOEventLoop线程循环执行的步骤
    1)轮询注册到自己selector上的所有NioSocketChannel 的read, write事件
    2)处理 I/O 事件, 即read , write 事件, 在对应NioSocketChannel 处理业务
    3)runAllTasks处理任务队列TaskQueue的任务 ,一些耗时的业务处理。一般可以放入 TaskQueue中慢慢处理,这样不影响数据在 pipeline 中的流动处理
  • 每个worker NIOEventLoop处理NioSocketChannel业务时,会使用 pipeline (管道),管道中维护 了很多 handler 处理器用来处理 channel 中的数据

Netty组件

  • Bootstrap、ServerBootstrap
    Bootstrap 意思是引导,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程 序,串联各个组件,Netty 中 Bootstrap 类是客户端程序的启动引导类,ServerBootstrap 是服务端 启动引导类。
  • Future、ChannelFuture
    在 Netty 中所有的 IO 操作都是异步的,不能立刻得知消息是否被正确处理。 但是可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过 Future 和 ChannelFutures,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事 件
  • Channel
    1)当前网络连接的通道的状态(例如是否打开?是否已连接?)
    2)网络连接的配置参数 (例如接收缓冲区大小)
    3)提供异步的网络 I/O 操作(如建立连接,读写,绑定端口),异步调用意味着任何 I/O 调用都将立即 返回,并且不保证在调用结束时所请求的 I/O 操作已完成。
    4)调用立即返回一个 ChannelFuture 实例,通过注册监听器到 ChannelFuture 上,可以 I/O 操作成 功、失败或取消时回调通知调用方。
    5)支持关联 I/O 操作与对应的处理程序
NioSocketChannel 异步的客户端TCP Socket连接
NioServerSocketChannel 异步的服务器端TCP Socket连接
NioDatagramChannel 异步的UDP连接
NioSctpChannel,异步的客户端 Sctp 连接。
NioSctpServerChannel,异步的 Sctp 服务器端连接。
这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO。
  • Selector
    Netty基于Selector对象实现I/O多路复用,通过Selector一个线程可以监听多个连接的Channel时间。当向一个Selector中注册Channel后,Selector内部的机制就可以不断轮询这些注册的Channel是否有就绪的I/O时间(读写、连接),这样程序就可以很简单地使用一个线程高效地管理多个 Channel 。

  • NioEventLoop
    NioEventLoop中维护了一个线程和任务队列,支持异步提交执行任务、线程启动时会调用NioEventLoop的run方法、执行I/O任务和非I/O任务;

  1. I/O 任务,即 selectionKey 中 ready 的事件,如 accept、connect、read、write 等,由 processSelectedKeys 方法触发。
  2. 非 IO 任务,添加到 taskQueue 中的任务,如 register0、bind0 等任务,由 runAllTasks 方法触发。
  • NioEventLoopGroup
    NioEventLoopGroup主要管理eventLoop的生命周期、可以理解为一个线程池,内部维护了一组线程,每个线程(NIOEventLoop)负责处理多个Channel上的时间,而一个Channel只对应一个线程

  • ChannelHandler
    ChannelHandler 是一个接口,处理 I/O 事件或拦截 I/O 操作,并将其转发到其 ChannelPipeline(业务处理链)中的下一个处理程序。
    ChannelHandler 本身并没有提供很多方法,因为这个接口有许多的方法需要实现,方便使用期间,可以继承它的子类:

ChannelInboundHandler 用于处理入站 I/O 事件。
ChannelOutboundHandler 用于处理出站 I/O 操作。

或者使用以下适配器类:

ChannelInboundHandlerAdapter 用于处理入站 I/O 事件。
ChannelOutboundHandlerAdapter 用于处理出站 I/O 操作。
  • ChannelHandlerContext
    保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象。
  • ChannelPipline
    保存ChannelHandler的双向链表、用于处理或者拦截Channel的入站和出站操作;
    ChannelPipeline实现了一种高级形式的拦截过滤器模式,是用户可以完全控制时间的处理方式、以及Channel中各个的ChannelHandler如何交互。
    在Netty中的每个Channel都有一个ChannelPipeline与之对应。
    在这里插入图片描述
    一个 Channel 包含了一个 ChannelPipeline,而 ChannelPipeline 中又维护了一个由 ChannelHandlerContext 组成的双向链表,并且每个 ChannelHandlerContext 中又关联着一个 ChannelHandler。
    read事件(入站事件)和write事件(出站事件)在一个双向链表中,入站事件会从链表 head 往后传递到最后一个入站的 handler,出站事件会从链表 tail 往前传递到最前一个出站的 handler,两种类型的 handler 互不干扰。

Netty示例代码

服务端

package com.Netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup  workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap=new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast((ChannelHandler) new NettyServerHandler());
                        }
                    });

            System.out.println("netty server start");

            ChannelFuture channelFuture = bootstrap.bind(9000).sync();
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()){
                        System.out.println("监听9000端口成功");
                    }else{
                        System.out.println("监听9000端口失败");
                    }
                }
            });
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
package com.Netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyServerHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务器读取线程:"+Thread.currentThread().getName());
        ByteBuf buf= (ByteBuf) msg;
        System.out.println("客户消息:"+buf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf = Unpooled.copiedBuffer("helloClient", CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

客户端

package com.Netty.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup loopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            System.out.println("netty client start");

            ChannelFuture channelFuture=bootstrap.connect("127.0.0.1",9000).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            loopGroup.shutdownGracefully();
        }
    }
}
package com.Netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf = Unpooled.copiedBuffer("helloServer", CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf= (ByteBuf) msg;
        System.out.println("收到服务端信息:"+ byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("服务端的地址: " + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值