学习Netty看我这篇就足矣!!!

Netty概述

为什么使用Netty

前面了解过的NIO模型,它有可靠性高、吞吐量高的优点,但也存在编程复杂的问题,我们要掌握大量的API,如:各种Channel、Buffer、Selector,还要编程处理特殊情况,如:异常处理、断线重连、心跳包等。

Netty对JDK自带的NIO包进行了大量的封装,较好的解决了上述问题,让我们既获得NIO模型性能高、资源消耗小、可靠性高等优点,又降低了编程的难度,所以目前进行网络编程时常用Netty框架。

Netty的应用场景

  1. 网络游戏服务器

    网络游戏服务器领域也大量使用了Java语言,Netty作为高性能的网络通信框架,得到了广泛的应用。

  2. 互联网应用

    分布式系统中各个节点的通信都可以使用Netty实现,如著名的RPC框架 Dubbo以及消息中间件 RocketMQ内部都采用了Netty。

  3. 大数据

    Hadoop体系中的Avro数据序列化系统,采用了Netty实现的RPC服务器

Netty入门案例

maven依赖

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.35.Final</version>
</dependency>

服务器

public class NettyServer {

    public static void main(String[] args) throws Exception {
        //处理连接请求的线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        //处理客户端业务的线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try {
            //创建服务器端的启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置两个线程组
            bootstrap.group(bossGroup, workerGroup)
                    //使用NioServerSocketChannel作为服务器的通道实现
                    .channel(NioServerSocketChannel.class) 
                    // 初始化服务器连接队列大小,服务端将不能处理的客户端连接请求放在队列中等待处理
                    .option(ChannelOption.SO_BACKLOG, 100)
                    // 创建通道初始化对象,设置初始化参数
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //对workerGroup的SocketChannel设置处理器
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("Server start");
            //启动服务器,bind是异步操作,sync方法是等待异步操作执行完毕
            ChannelFuture cf = bootstrap.bind(9000).sync();
            // 对通道关闭进行监听,closeFuture是异步操作,通过sync方法同步等待通道关闭处理完毕
            cf.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

服务器的处理器

/**
 * 自定义Handler
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取客户端发送的数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("服务器读取线程 " + Thread.currentThread().getName());
        //将 msg 转成一个 ByteBuf,类似NIO 的 ByteBuffer
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端发送消息是:" + buf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 数据读取完毕处理方法
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("Hello Client".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(buf);
    }

    /**
     * 处理异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

客户端

public class NettyClient {
    public static void main(String[] args) throws Exception {
        //客户端线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置线程组
            bootstrap.group(group)
                    // 使用NioSocketChannel作为客户端的通道实现
                    .channel(NioSocketChannel.class) 
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //加入处理器
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            System.out.println("Client start");
            //启动客户端去连接服务器端
            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();
            //对通道关闭进行监听
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}

客户端处理器

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 客户端连接服务器完成
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("Hello Server".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(buf);
    }

 	/**
     * 当通道有读取事件时会触发,即服务端发送数据给客户端
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("收到服务端的消息:" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务端的地址: " + ctx.channel().remoteAddress());
    }

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

Netty工作模型

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-td2rqwux-1655164395139)(Netty基础.assets/1644371150805.png)]

工作模型介绍

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

Netty组件介绍

  • Bootstrap、ServerBootstrap
    Bootstrap 意思是引导,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联各个组件,Netty 中 Bootstrap 类是客户端程序的启动引导类,ServerBootstrap 是服务端启动引导类。

  • Future、ChannelFuture
    在 Netty 中所有的 IO 操作都是异步的,不能立刻得知消息是否被正确处理。
    但是可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过 Future 和ChannelFutures,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件。

  • Channel
    Netty 网络通信的组件,能够用于执行网络 I/O 操作。

    Channel 为用户提供:
    1)当前网络连接的通道的状态(例如是否打开?是否已连接?)
    2)网络连接的配置参数 (例如接收缓冲区大小)
    3)提供异步的网络 I/O 操作(如建立连接,读写,绑定端口),异步调用意味着任何 I/O 调用都将立即返回,且不保证在调用结束时所请求的 I/O 操作已完成。
    4)调用立即返回一个 ChannelFuture 实例,通过注册监听器到 ChannelFuture 上,可以 I/O 操作成功、失败或取消时回调通知调用方。
    5)支持关联 I/O 操作与对应的处理程序。
    不同协议、不同的阻塞类型的连接都有不同的 Channel 类型与之对应。
    下面是一些常用的 Channel 类型:
    1 NioSocketChannel,异步的客户端 TCP Socket 连接。
    2 NioServerSocketChannel,异步的服务器端 TCP Socket 连接。
    3 NioDatagramChannel,异步的 UDP 连接。
    4 NioSctpChannel,异步的客户端 Sctp 连接。
    5 NioSctpServerChannel,异步的 Sctp 服务器端连接,这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO。

  • Selector
    Netty 基于 Selector 对象实现 I/O 多路复用,通过 Selector 一个线程可以监听多个连接的 Channel事件。
    当向一个 Selector 中注册 Channel 后,Selector 内部的机制就可以自动不断地查询(Select) 这些注册的 Channel 是否有已就绪的 I/O 事件(例如可读,可写,网络连接完成等),这样程序就可以很简单地使用一个线程高效地管理多个 Channel 。

  • NioEventLoop
    NioEventLoop 中维护了一个线程和任务队列,支持异步提交执行任务,线程启动时会调用NioEventLoop 的 run 方法,执行 I/O 任务和非 I/O 任务:
    I/O 任务,即 selectionKey 中 ready 的事件,如 accept、connect、read、write 等,由processSelectedKeys 方法触发。
    非 IO 任务,添加到 taskQueue 中的任务,如 register0、bind0 等任务,由 runAllTasks 方法触发。

  • NioEventLoopGroup
    NioEventLoopGroup,主要管理 eventLoop 的生命周期,可以理解为一个线程池,内部维护了一组线程,每个线程(NioEventLoop)负责处理多个 Channel 上的事件,而一个 Channel 只对应于一个线程。

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

  • ChannelHandlerContext
    保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象。

  • ChannelPipline
    保存 ChannelHandler 的 List,用于处理或拦截 Channel 的入站事件和出站操作。
    ChannelPipeline 实现了一种高级形式的拦截过滤器模式,使用户可以完全控制事件的处理方式,以
    及 Channel 中各个的 ChannelHandler 如何相互交互。
    在 Netty 中每个 Channel 都有且仅有一个 ChannelPipeline 与之对应,它们的组成关系如下:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dQHfAQPk-1655164395142)(Netty基础.assets/1644371829399.png)]

    一个 Channel 包含了一个 ChannelPipeline,而 ChannelPipeline 中又维护了一个由
    ChannelHandlerContext 组成的双向链表,并且每个 ChannelHandlerContext 中又关联着一个
    ChannelHandler。
    read事件(入站事件)和write事件(出站事件)在一个双向链表中,入站事件会从链表 head 往后传递到最
    后一个入站的 handler,出站事件会从链表 tail 往前传递到最前一个出站的 handler,两种类型的
    handler 互不干扰

Netty聊天室

服务器

public class ChatServer {
    public static void main(String[] args) throws Exception {
        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 ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //向pipeline加入字符串解码器
                            pipeline.addLast(new StringDecoder());
                            //向pipeline加入字符串编码器
                            pipeline.addLast(new StringEncoder());
                            //加入自己的业务处理handler
                            pipeline.addLast(new ChatServerHandler());
                        }
                    });
            System.out.println("聊天室server启动");
            ChannelFuture channelFuture = bootstrap.bind(9000).sync();
            //关闭通道
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

服务器处理器

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    //全局通道组,所有通道都会加入到该组
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    
    //表示 channel 处于就绪状态, 提示上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户加入聊天的信息推送给其它在线的客户端
        channelGroup.writeAndFlush(channel.remoteAddress() + " 上线了\n");
        //将当前 channel 加入到 channelGroup
        channelGroup.add(channel);
        System.out.println(ctx.channel().remoteAddress() + " 上线了\n");
    }

    //表示 channel 处于不活动状态, 提示离线了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //将客户离开信息推送给当前在线的客户
        channelGroup.writeAndFlush(ctx.channel().remoteAddress() + " 下线了\n");
        System.out.println(ctx.channel().remoteAddress() + " 下线了\n");
    }

    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //将客户端的消息发送给所有用户
        channelGroup.writeAndFlush(ctx.channel().remoteAddress() + "说:" + msg + "\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}

客户端

public class ChatClient {

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

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            //设置客户端处理器
                            pipeline.addLast(new ChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000).sync();
            //得到 channel
            Channel channel = channelFuture.channel();
            //客户端输入信息
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                //通过 channel 发送到服务器端
                channel.writeAndFlush(msg);
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}

客户端处理器

public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
    //读取服务器发来的数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg.trim());
    }
}


编码解码

回顾Netty的几个组件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NFOJS8hJ-1655164528953)(Netty高级.assets/1644374090578.png)]

  • Channel

    服务器和客户端建立的连接通道

  • ChannelPipeline

    管道,一个通道包含一个管道,管道包含一个处理器链

  • ChannelHandler

    管道中的处理器链包含多个处理器,每个处理器可以处理不同的IO事件,是双向链表结构,包含head头部和tail尾部。

    处理器分为:

    • ChannelInboundHandler

      入站消息处理器(处理进入的消息)

    • ChannelOutboundHandler

      出站消息处理器(处理出去的消息)

编码和解码

Netty在接收和发送消息时都需要进行数据转换。接收消息时(入站)需要把字节转换为自己的格式(字符串、对象等)这就是解码。发送消息时把自己的格式转换为字节,就是编码。

编码器继承MessageToMessageEncoder类 ,实现了ChannelOutboundHandler 接口

解码器继承MessageToMessageDecoder类,实现了ChannelInboundHandler接口

Netty自带的编码解码器有:

  • StringEncoder字符串编码器
  • StringDecoder字符串解码器
  • ObjectEncoder对象编码器
  • ObjectDecoder对象解码器
 bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //向pipeline加入字符串解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            //向pipeline加入字符串编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            //加入自己的业务处理handler
                            pipeline.addLast(new ChatServerHandler());
                        }
                    });

以聊天室程序为例,先在管道中加入了字符串解码器,这样就能将字节转换为字符串,读取打印出来;然后加入了字符串编码器,这些在发送数据时,将字符串转换为字节发送出去。

自定义编码和解码器

开发者可以自定义编码解码器

自定义解码器

/**
 * byte转long解码器
 */
public class ByteToLongDecoder extends ByteToMessageDecoder {

	//重写编码方法
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("解码方法被调用");
        //读取长整型需要的8个字节
        if(in.readableBytes() >= 8) {
            out.add(in.readLong());
        }
    }

}

自定义解码器

/**
 * long转byte编码器
 */
public class LongToByteEncoder extends MessageToByteEncoder<Long> {

    //重写编码方法
    @Override
    protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
        System.out.println("编码方法被调用 " + msg);
        out.writeLong(msg);
    }
}

服务器和客户端在添加处理器时,可以加入编码器和解码器

public class NettyServer {
    public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //给服务器添加了long类型的解码器和编码器
                            pipeline.addLast(new ByteToLongDecoder());
                            pipeline.addLast(new LongToByteEncoder());
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            System.out.println("netty server start。。");
            ChannelFuture channelFuture = serverBootstrap.bind(9000).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

服务器和客户端的业务处理器中,就可以读取和发送long的数据

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("从客户端读取到Long:" + (Long)msg);
        //给客户端发回一个long数据
        ctx.writeAndFlush(2000L);
    }
}

粘包拆包

Netty是基于TCP协议的,TCP是面向流的,数据没有边界,操作系统在发送时会通过缓冲区进行优化,缓冲区有固定大小,如1024字节。

粘包

​ 如果一次发送数据时,数据量没有达到缓冲区大小,TCP会将多个数据包合到一起发送,这样就形成了粘包

拆包

​ 如果一次发送数据时,数据量超过了缓冲区大小,TCP会将数据拆分成多个数据包发送,这样就是拆包

如下图所示,出现几种情况

  1. 理想情况,两次发送的数据包正好是缓冲区大小,就正常作为两个数据包发送
  2. 出现粘包,两次发送的数据包加一起等于缓冲区大小,将两个包合并为一个包发送
  3. 出现拆包,一次发送的包超过了缓冲区,分成了多个包发送
  4. 拆包/粘包同时发生,一个包比缓冲区大,一个比缓冲区小,会将大的包拆开和小的包合并到一起发送

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iVNg2NIO-1655164528954)(Netty高级.assets/1644377524859.png)]

数据一般有完整性,如:文件、字符串等,发生粘包和拆包会导致数据出现混乱。

解决方案:

  1. 规定固定长度,如100字节,按长度拆分
  2. 设置某些字符作为分隔符,如:\r\n,读取后按分隔符进行数据拆分
  3. 数据包中包含长度,读取到后对数据进行拆分
  4. 使用特定的协议,消息头中包含长度,进行粘包和拆包处理

Netty提供了一些解码器(Decoder)来解决粘包和拆包的问题。如:

  • LineBasedFrameDecoder 以行(\r\n)为单位进行数据包的解码;
  • DelimiterBasedFrameDecoder:以特殊的符号作为分隔来进行数据包的解码;
  • FixedLengthFrameDecoder:以固定长度进行数据包的解码;
  • LengthFieldBasedFrameDecoder:适用于消息头包含消息长度的协议;

零拷贝

Java的内存按分配位置分为:

  • 堆内内存(JVM堆中分配的内存)
  • 直接内存(JVM外部分配的内存)

Socket网络通信时,数据通过网络发送到网卡,先通过网卡保存到直接内存中,再从直接内存中把数据复制到JVM堆中,才能对数据进行操作。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OPC9d07u-1655164528954)(Netty高级.assets/1644390122004.png)]

Netty采用的是零拷贝机制,在JVM中直接引用直接内存中的数据,不需要进行拷贝,提高了IO效率。

在这里插入图片描述

ByteBuffer类的allocate方法用于分配堆内内存,allocateDirect方法用于分配直接内存

/**
 * 直接内存与堆内存的区别
 */
public class DirectMemoryTest {

    /**
     * 访问堆内存
     */
    public static void heapAccess() {
        long startTime = System.currentTimeMillis();
        //分配堆内存
        ByteBuffer buffer = ByteBuffer.allocate(1000);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("堆内存访问:" + (endTime - startTime));
    }

    /**
     * 访问直接内存
     */
    public static void directAccess() {
        long startTime = System.currentTimeMillis();
        //分配直接内存
        ByteBuffer buffer = ByteBuffer.allocateDirect(1000);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();
            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("直接内存访问:" + (endTime - startTime));
    }

    /**
     * 分配堆内存
     */
    public static void heapAllocate() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            ByteBuffer.allocate(100);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("堆内存申请:" + (endTime - startTime));
    }

    /**
     * 分配直接内存
     */
    public static void directAllocate() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            ByteBuffer.allocateDirect(100);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("直接内存申请:" + (endTime - startTime));
    }

    public static void main(String args[]) {
        for (int i = 0; i < 5; i++) {
            heapAccess();
            directAccess();
        }
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            heapAllocate();
            directAllocate();
        }
    }
}

通过运行结果可以看到:堆内存的访问效率低于直接内存,堆内存的分配速度高于直接内存

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mEEiPIYU-1655164528956)(Netty高级.assets/1644391123149.png)]

使用直接内存的优缺点:
优点:

  1. 不占用堆内存空间,减少了发生GC的可能

  2. java虚拟机实现上,本地IO会直接操作直接内存(直接内存=>系统调用=>硬盘/网卡),而非直接内存则需要二次拷贝(堆内存=>直接内存=>系统调用=>硬盘/网卡)

缺点:

  1. 初始分配较慢
  2. 没有JVM直接帮助管理内存,容易发生内存溢出。为了避免一直没有FULL GC,最终导致直接内存把物理内存被耗完。我们可以指定直接内存的最大值,通过-XX:MaxDirectMemorySize来指定,当达到阈值的时候,调用system.gc来进行一次FULL GC,间接把那些没有被使用的直接内存回收掉。

心跳检测

TCP在长连接时,会定期在客户端和服务器之间发送心跳包(一种很小的数据包),通知对方自己在线,一旦长期收不到心跳包,则认为对方离线,自己可以进行异常处理。

Netty的IdleStateHandler可以实现心跳检测机制

构造方法

IdleStateHandler(int readerIdleTime, int writerIdleTime, int allIdleTime,TimeUnit unit )

参数:

  1. readerIdleTime: 读超时. 即当在指定的时间间隔内没有从 Channel 读取到数据时会触发
  2. writerIdleTime: 写超时. 即当在指定的时间间隔内没有数据写入到 Channel 时会触发
  3. allIdleTime: 读/写超时. 即当在指定的时间间隔内没有读或写操作时会触发
  4. unit 时间单位

带心跳检测机制的服务器端

添加了IdleStateHandler,并设置读超时为3秒,3秒没有读取客户端消息则会触发下一个处理器中的userEventTriggered方法

public class HeartBeatServer {

    public static void main(String[] args) throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            //IdleStateHandler的readerIdleTime参数指定超过3秒还没收到客户端的连接,
                            //会触发IdleStateEvent事件并且交给下一个handler处理,下一个handler必须
                            //实现userEventTriggered方法处理对应事件
                            pipeline.addLast(new IdleStateHandler(3, 0, 0, TimeUnit.SECONDS));
                            pipeline.addLast(new HeartBeatServerHandler());
                        }
                    });
            System.out.println("netty server start。。");
            ChannelFuture future = bootstrap.bind(9000).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}


服务器处理器

重写了userEventTriggered方法,执行心跳超时的处理逻辑

public class HeartBeatServerHandler extends SimpleChannelInboundHandler<String> {

    int readIdleTimes = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        System.out.println(" ====== > [server] message received : " + s);
        if ("Heartbeat Packet".equals(s)) {
            ctx.channel().writeAndFlush("ok");
        } else {
            System.out.println(s);
        }
    }

    //触发超时事件
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;

        String eventType = null;
        switch (event.state()) {
            case READER_IDLE:
                eventType = "读空闲";
                readIdleTimes++; // 读空闲的计数加1
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                // 不处理
                break;
            case ALL_IDLE:
                eventType = "读写空闲";
                // 不处理
                break;
        }
        System.out.println(ctx.channel().remoteAddress() + "超时事件:" + eventType);
        if (readIdleTimes > 3) {
            System.out.println(" [server]读空闲超过3次,关闭连接,释放更多资源");
            ctx.channel().writeAndFlush("idle close");
            ctx.channel().close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("=== " + ctx.channel().remoteAddress() + " is active ===");
    }
}

客户端定期发送心跳数据包

public class HeartBeatClient {
    public static void main(String[] args) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new HeartBeatClientHandler());
                        }
                    });

            System.out.println("netty client start。。");
            Channel channel = bootstrap.connect("127.0.0.1", 9000).sync().channel();
            String text = "Heartbeat Packet";
            Random random = new Random();
            //随机时间间隔发送心跳包
            while (channel.isActive()) {
                int num = random.nextInt(10);
                Thread.sleep(num * 1000);
                channel.writeAndFlush(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    static class HeartBeatClientHandler extends SimpleChannelInboundHandler<String> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println(" client received :" + msg);
            if (msg != null && msg.equals("idle close")) {
                System.out.println(" 服务端关闭连接,客户端也关闭");
                ctx.channel().closeFuture();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值