栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

netty 基础概述

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

netty 基础概述


netty 基础概述

       

               

                                   

基本特性

            

                

 i/o模式:同时支持阻塞、非阻塞i/o,可实现异步非阻塞通信

零拷贝:使用堆外内存直接读写,不需要进行内存复制

内存缓冲:使用内存池,复用缓冲区的内存

reactor线程模型:单线程、多线程、主从多线程

无锁化串行:使用channel pipeline,使任务在同一个线程中执行,不需要进行线程切换

序列化:默认使用protobuf,也可通过扩展接口使用其他序列化框架

          

               

                                   

线程模型

     

单线程:用一个线程中处理不同客户端请求(建立连接、编解码、业务逻辑处理等)

                

         

多线程:使用多线程处理不同客户端的请求

                

acceptor:处理客户端连接,将建立后的连接发送给reactor thread pool做后续处理

reactor thread pool:使用线程池进行编解码、业务逻辑处理

           

主从多线程:多线程处理客户端连接,多线程执行后续操作

                

main reactor threadpool:使用线程池处理客户端连接(包括请求认证等)

sub reactor threadpool:使用线程池进行编解码、业务逻辑处理等

       

              

                                   

内存管理

  

*************

内存划分

         

netty可使用堆内存、直接内存,并使用内存池进行内存复用

                

UnpooledHeapByteBuf:非池化堆内存
UnpooledUnsafeHeapByteBuf:非池化的unsafe堆内存
UnpooledDirectByteBuf:非池化的直接内存(堆外内存)
UnpooledUnsafeDirectteBuf:非池化的unsafe直接内存(堆外内存)

PooledHeapByteBuf:池化堆内存
PooledUnsafeHeapByteBuf:池化的unsafe堆内存
PooledDirectByteBuf:池化的直接内存(堆外内存)
PooledUnsafeDirectteBuf:池化的unsafe直接内存(堆外内存)

             

*************

零拷贝

         

传统数据复制过程:磁盘 ==> 系统缓存 ==> 用户内存 ==> socket buffer ==> 网卡设备

                

          

mmap实现零拷贝:磁盘 ==> 系统内存 ==>  socket buffer ==> 网卡设备

                

           

 sendfile实现零拷贝:磁盘 ==> 系统内存(复制文件描述符到socket buffer,不复制数据)==> 网卡设备

                

          

netty 零拷贝

# 使用直接内存
直接操作堆外内存(direct buffer),不需要将数据复制到堆内存;

# 组合ByteBuf
CompositeByteBuf可将多个ByteBuf组合起来,不需要做数据复制;

# 文件传输零拷贝
文件传输调用FileChannel transferTo方法(底层使用sendFile实现),
不需要将数据复制到socket buffer,直接将缓冲区的数据发送到目标channel

          

*************

内存泄漏检测

    

直接内存需要手动释放,否则会存在内存泄漏的风险,netty提供了内存泄漏检测机制

          

AbstractbyteBufAllocator:内存分配器(包含内存泄漏检测)

public abstract class AbstractByteBufAllocator implements ByteBufAllocator {

    protected static ByteBuf toLeakAwareBuffer(ByteBuf buf) {
                                              //追踪检测BuyteBuf
        ResourceLeakTracker leak;
        switch(ResourceLeakDetector.getLevel()) {
        case SIMPLE:
            leak = AbstractByteBuf.leakDetector.track(buf);   //泄漏检测器追踪byteBuf使用状况
            if (leak != null) {
                buf = new SimpleLeakAwareByteBuf((ByteBuf)buf, leak);
            }   //SIMPLE监控级别,使用SimpleLeakAwareByteBuf包装buf对象
            break;
        case ADVANCED:
        case PARANOID:
            leak = AbstractByteBuf.leakDetector.track(buf);
            if (leak != null) {
                buf = new AdvancedLeakAwareByteBuf((ByteBuf)buf, leak);
            }   //ADVANCED、PARANOID监控级别,使用AdvancedLeakAwareByteBuf包装buf对象
        }

        return (ByteBuf)buf;
    }

    protected static CompositeByteBuf toLeakAwareBuffer(CompositeByteBuf buf) {
                                      //追踪检测CompositeByteBuf
        ResourceLeakTracker leak;
        switch(ResourceLeakDetector.getLevel()) {
        case SIMPLE:
            leak = AbstractByteBuf.leakDetector.track(buf);
            if (leak != null) {
                buf = new SimpleLeakAwareCompositeByteBuf((CompositeByteBuf)buf, leak);
            }
            break;
        case ADVANCED:
        case PARANOID:
            leak = AbstractByteBuf.leakDetector.track(buf);
            if (leak != null) {
                buf = new AdvancedLeakAwareCompositeByteBuf((CompositeByteBuf)buf, leak);
            }
        }

        return (CompositeByteBuf)buf;
    }

           

ResourceLeakDetector:资源泄漏探测器

public class ResourceLeakDetector {

    public final ResourceLeakTracker track(T obj) {
        return this.track0(obj);
    }

    private ResourceLeakDetector.DefaultResourceLeak track0(T obj) {
        ResourceLeakDetector.Level level = ResourceLeakDetector.level;
        if (level == ResourceLeakDetector.Level.DISABLED) {
            return null;
        } else if (level.ordinal() < ResourceLeakDetector.Level.PARANOID.ordinal()) {
            if (PlatformDependent.threadLocalRandom().nextInt(this.samplingInterval) == 0) {
                this.reportLeak();   //报告内存使用状态
                return new ResourceLeakDetector.DefaultResourceLeak(obj, this.refQueue, this.allLeaks, this.getInitialHint(this.resourceType));
            } else {
                return null;
            }
        } else {
            this.reportLeak();       //报告内存使用状态
            return new ResourceLeakDetector.DefaultResourceLeak(obj, this.refQueue, this.allLeaks, this.getInitialHint(this.resourceType));
        }
    }


********
内部枚举:ResourceLeakDetector.Level

    public static enum Level {  //资源监控级别
        DISABLED,
        SIMPLE,
        ADVANCED,
        PARANOID;

          

                  

                                   

客户端启动

    

NettyClient

public class NettyClient {

    public static void connect(String host, int port){
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();  //客户端执行任务的线程组

        try {
            Bootstrap bootstrap = new Bootstrap();   //客户端启动器
            bootstrap.group(eventLoopGroup)          //设置工作线程组
                    .channel(NioSocketChannel.class) //设置channel类型
                    .option(ChannelOption.SO_KEEPALIVE, true)   //channel参数
                    .handler(new ChannelInitializer() { 
                                  //channel初始化

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                                                                 //获取channel对应的pipeline,每个channel都有一个对应的pipeline
                            channelPipeline.addLast(new CustomChannel());
                            channelPipeline.addLast(new CustomChannel2());
                                            //添加自定义的channel,进行编解码、业务逻辑处理等操作
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
                                          //向服务端发器同步连接请求,
                                          //连接过程中会将channel注册到selector上(i/o多路复用技术)
            channelFuture.channel().closeFuture().sync();  //连接关闭处理
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();  //释放资源(关闭eventLoopGroup线程池)
        }
    }

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8000;
        connect(host, port);
    }
}

           

             

                                   

服务端启动

   

NettyServer

public class NettyServer {

    public static void startServer(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();   //主线城池,处理客服端连接
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //工作线程池,进行编解码、业务逻辑处理等

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();  //服务端启动器
            serverBootstrap.group(bossGroup, workerGroup)     //设置主线程池、工作线程池
                    .channel(NioServerSocketChannel.class)    //设置channel类型
                    .option(ChannelOption.SO_BACKLOG, 128)    //设置主线程参数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //设置工作线程参数
                    .handler(new ChannelInitializer() {
                                 //channel初始化

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                                            //获取pipeline,每个channel都有一个pileline与其对应
                            channelPipeline.addLast(new CustomChannel());
                            channelPipeline.addLast(new CustomChannel());
                        }                   //添加自定义的handler
                    });

            System.out.println("启动服务端,开启服务监听");
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
                                            //绑定端口,开启服务监听
                                            //绑定端口时,会将channel注册到selector上(i/o多路复用技术)
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        startServer(8080);
    }
}

           

                  

                                   

编解码

  

tcp 粘包、拆包:tcp发送数据时,并不关心上层数据具体含义,会根据实际情况对数据进行查分或者合并

                

粘包:客户端发送数据时,将多个数据包合并发送

拆包(半包):如果单个数据包数据量比较大(如文件等),会将数据包进行拆分

             

粘包解决方案:

消息定长:如消息固定长度200,不阻塞用空格补齐
使用分隔符:报尾添加特殊分隔符,接收方通过分隔符区分报文
使用消息头、消息体:在消息头重定义消息总长度
自定义应用层协议:如设置应用层数据长度固定,不足补空位

说明:netty内置的编解码器已经对粘包、拆包做了处理

               

常用编码器

MessageToByteEncoder:编码器抽象类

ProtobufVarint32LengthFieldPrepender:使用protobuf序列化编码
ObjectEncoder:java序列化编码器
Bzip2Encoder:bzip2编码器
FastLzFrameEncoder:fastLz编码器
JdkZlibEncoder:zib压缩编码器
LzfEncoder:lzf压缩编码

            

常用解码器

ByteToMessageDecoder:解码器抽象类,抽象类没有处理粘包、拆包,子类处理了粘包、拆包

LineBasedFrameDecoder:发送的消息以"n"、"rn"结尾,可用该解码器解码
DelimiterBasedFrameDecoder:按照用户指定的分隔符解码
FixedLengthFrameDecoder:固定长度解码器
LengthFieldBasedFrameDecoder:读取指定偏移位置、数据长度的解码器

                     

                

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/919827.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号