0592 网站建设,南京市住房和城乡建设网站,网页制作公司,深圳工程交易中心网【README】
本文总结自B站《尚硅谷-netty》#xff0c;很不错#xff1b; 内容如下#xff1a; netty的编码器与解码器#xff1b;netty客户端与服务器通过 protobuf 传输报文的开发方式#xff1b;文末po出了所有代码#xff1b;【1】netty的编码器与解码器 codec
1很不错 内容如下 netty的编码器与解码器netty客户端与服务器通过 protobuf 传输报文的开发方式文末po出了所有代码【1】netty的编码器与解码器 codec
1编解码器应用场景
编写网络应用程序时因为数据在网络中传输的都是二进制字节码数据在发送数据时就需要编码接收数据时就需要解码 如下图【图1】 编码与解码流程图 2 codec(编解码器) 的组成部分有两个decoder(解码器)和encoder(编码器)。
encoder 负责把业务数据如pojo对象转换成字节码数据decoder 负责把字节码数据转换成业务数据如pojo对象
补充 编解码器对应的英文“codec”compress和decompress简化而成的合成词语 )from wikipedia
3java序列化的问题所以才引入了 protobuf
Netty 本身自带的 ObjectDecoder 和 ObjectEncoder 可以用来实现POJO对象或各种业务对象的编码和解码底层使用的仍是 Java 序列化技术 , 而Java 序列化技术本身效率就不高存在如下问题 无法跨语言 序列化后的体积太大是二进制编码的 5 倍多 序列化性能太低
引入新的解决方案 google 的 Protobuf 【2】Protobuf
【2.1】概述
0 intro2 protobuf, refer2 https://developers.google.com/protocol-buffers ;
1ProtoBuf定义
是 Protocol Buffer 的缩写即协议缓冲区它是google实现的一种开源跨平台的序列化资料结构的协议。
2ProtoBuf 是google提出的结构数据序列化方法可简单类比于 XML其具有以下特点
① 语言无关、平台无关。即 ProtoBuf 支持 Java、C、Python 等多种语言支持多个平台② 高效。即比 XML 更小3 ~ 10倍、更快20 ~ 100倍、更为简单③ 扩展性、兼容性好。你可以更新数据结构而不影响和破坏原有的旧程序
【小结】
说的直接点 protobuf序列化性能 优于 java序列化因为protobuf 很适合做数据存储或 RPC[远程过程调用]数据交换格式所以目前有些公司把远程调用的报文传输方式从 httpjson 修改为 tcpprotobuf
3基于protobuf的编码与解码流程 【图解】 使用protobuf序列化 java对象的步骤
步骤1编写 proto 文件步骤2使用 protoc.exe 编译把 proto文件编译为 java文件pojo文件步骤3创建pojo对象并赋值发送到服务器
【补充】关于 protobuf的更多介绍refer2 https://www.jianshu.com/p/a24c88c0526a 【2.2】 netty客户端服务器通过protobuf传输报文
说明
为了清晰展示 protobuf 的开发方式下文使用了截图但 netty通过 protobuf 传输报文的所有代码会在文末po出
【步骤1】 引入 protobuf 依赖
dependencygroupIdcom.google.protobuf/groupId artifactIdprotobuf-java/artifactIdversion3.6.1/version
/dependency
【步骤2】编写 proto 文件
Student.proto
syntaxproto3; // 版本
option java_outer_classname StudentPOJO; // 生成的外部类名同时也是文件名
// protobuf 使用 message 管理数据
message Student { // 会在 StudentPOJO 外部类生成一个内部类 Student他是真正方发送的POJO对象int32 id 1; // Student类中有一个属性属性名为 id类型为 int32; 1 表示属性序号并不是属性值string name 2;}
【步骤3】编译 proto文件到 POJO javabean 文件
编译命令
protoc.exe --java_out. Student.proto
【补充】
protoc.exe 编译器到这个地方 Central Repository: com/google/protobuf/protoc/3.6.1 下载并录入到path系统环境变量生成的 javabean文件为 StudentPOJO.java 【步骤4】 客户端发送 Student 对象到服务器
1客户端添加 protobuf 编码器 ProtobufEncoder; 2 客户端处理器
根据 protobuf编译成的 POJO类文件创建对应javabean对象并发送到服务器【步骤5】 服务器解码protobuf字节码
添加 protobuf解码器 ProtobufDecoder netty服务器 处理器接收POJO类对象pojo类是由protobuf编译而成 【演示结果】netty客户端与服务器使用 probobuf传输报文 【3】netty 使用 protobuf传输报文的客户端与服务器代码源代码
【3.1】netty服务器
1netty服务器 注意它添加的protobuf解码器 ProtobufDecoder
public class ProtobufNettyServer76 {public static void main(String[] args) throws InterruptedException {// 创建 BossGroup 和 WorkerGroup// 1. 创建2个线程组 bossGroup workerGroup// 2 bossGroup 仅处理连接请求 真正的业务逻辑交给workerGroup完成// 3 两个线程组都是无限循环// 4 bossGroup 和 workerGroup 含有的子线程NIOEventLoop个数// 默认是 cpu核数 * 2EventLoopGroup boosGroup new NioEventLoopGroup();EventLoopGroup workerGruop new NioEventLoopGroup();try {// 创建服务器端的启动对象 配置参数ServerBootstrap bootstrap new ServerBootstrap();bootstrap.group(boosGroup, workerGruop) // 设置2个线程组.channel(NioServerSocketChannel.class) // 使用NIOSocketChannel 作为服务器的通道实现.option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列等待连接的个数.childOption(ChannelOption.SO_KEEPALIVE, true) // 设置保持活动连接状态.childHandler(new ChannelInitializerSocketChannel() { // 创建一个通道初始化对象// 给 pipeline 设置处理器Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline socketChannel.pipeline();// 添加 protobuf 解码器, 指定对哪种对象进行解码pipeline.addLast(decoder, new ProtobufDecoder(StudentPOJO.Student.getDefaultInstance()));// 添加业务处理器
// pipeline.addLast(new ProtobufNettyServerHandler());pipeline.addLast(new ProtobufNettyServerHandler2());}}); // 给我们的workerGroup 的 EventLoop 对应的管道设置处理器System.out.println(... server is ready.);// 启动服务器 绑定端口并同步处理 生成一个 ChannelFuture对象ChannelFuture channelFuture bootstrap.bind(6668).sync();channelFuture.addListener((future1) - System.out.println(Finish binding));// 给 channelFuture 注册监听器监听我们关心的事件channelFuture.addListener(future - {if (future.isSuccess()) {System.out.println(监听端口6668 成功);}else {System.out.println(监听端口6668 失败);}});// 对关闭通道进行监听channelFuture.channel().closeFuture().sync();} finally {// 优雅关闭boosGroup.shutdownGracefully();workerGruop.shutdownGracefully();}}
}2netty服务器处理器channelRead0方法中的 StudentPOJO.Student javabean就是由 protobuf编译生成的java类
public class ProtobufNettyServerHandler2 extends SimpleChannelInboundHandlerStudentPOJO.Student {// 读写数据事件读取客户端发送的消息// 1. ChannelHandlerContext ctx 上下文信息包括管道pipeline通道channel地址// 2. Object msg 客户端发送的数据默认是 ObjectOverridepublic void channelRead0(ChannelHandlerContext ctx, StudentPOJO.Student student) throws Exception {System.out.println(SimpleChannelInboundHandler子类handler-客户端发送的数据 id student.getId() name student.getName());}// 数据读取完毕回复客户端Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {// writeAndFlush 是 write flush ;把数据写入到缓冲并刷新ChannelFuture channelFuture ctx.writeAndFlush(Unpooled.copiedBuffer(hello, 客户端, StandardCharsets.UTF_8));channelFuture.addListener(future - System.out.println(回复成功));}// 处理异常关闭通道Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.channel().close();}
} 【3.2】netty客户端
1netty客户端 注意其添加的 Protobuf编码器 ProtobufEncoder
public class ProtobufNettyClient76 {public static void main(String[] args) throws InterruptedException {// 客户端需要一个事件循环组EventLoopGroup eventLoopGroup new NioEventLoopGroup();try {// 创建客户端启动对象 注意是 BootStrapBootstrap bootstrap new Bootstrap();// 设置相关参数bootstrap.group(eventLoopGroup) // 设置线程组.channel(NioSocketChannel.class) // 设置客户端通道实现类(反射).handler(new ChannelInitializerSocketChannel() {Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline socketChannel.pipeline();// 添加 ProtobufEncoder 编码器pipeline.addLast(new ProtobufEncoder());// 添加业务处理器pipeline.addLast(new ProtobufNettyClientHandler()); // 加入自己的处理器}});System.out.println(client is ok);// 启动客户端去连接服务器// ChannelFuture 设计到netty的异步模型ChannelFuture channelFuture bootstrap.connect(127.0.0.1, 6668).sync();// 给关闭通道进行监听channelFuture.channel().closeFuture().sync();} finally {eventLoopGroup.shutdownGracefully();}}
}
2netty客户端处理器 注意 channelActive方法中的 StudentPOJO.Student是由Protobuf编译生成的POJO类
public class ProtobufNettyClientHandler extends ChannelInboundHandlerAdapter {// 当通道就绪就会触发该方法Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {// 发送一个 StudentPOJO 对象到服务器StudentPOJO.Student student StudentPOJO.Student.newBuilder().setId(4).setName(zhangsan).build();ctx.writeAndFlush(student);}// 当通道有读取事件时会触发Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf byteBuf (ByteBuf) msg;System.out.println(服务器回复消息 byteBuf.toString(StandardCharsets.UTF_8) , 当前时间 DateUtils.getNowTimestamp());System.out.println(服务器地址 ctx.channel().remoteAddress());}// 捕获异常Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}