Protobuf
Protobuf支持多种编程语言,包括C++、Java、Python、Go、JavaScript等,这使得它非常适合在多语言环境中使用。Protobuf的序列化和反序列化过程非常快,因为它使用了二进制格式,相比于文本格式如JSON,可以显著减少数据大小和提高处理速度。相比XML,有编码后体积更小,编解码速度更快的优势;相比于 Json,Protobuf 有更高的转化效率,时间效率和空间效率都是 JSON 的 3-5 倍。通过定义.proto文件,Protobuf提供了工具(protoc编译器)来自动生成各种语言的数据访问类,这大大简化了开发工作。
数据格式
XML
<person><name>aaa</name><age>111</age>
</person>
JSON
{"name":"aaa","age":111
}
直接用二进制来表示数据,不像上面的XML和JSON格式那么直观。
[10 6 69 108 108 105 111 116 16 24]
优势
Protobuf作为一种高效的结构化数据交换格式,以其跨语言支持、快速的序列化与反序列化能力、以及自动生成代码的特性,在许多高性能分布式系统和微服务架构中发挥着重要作用。它的二进制格式不仅减少了网络传输的数据量,还提高了数据处理速度,特别适合于需要处理大量数据的场景。此外,Protobuf的向后兼容性和丰富的数据类型支持,使其成为数据存储和通信协议的理想选择。
缺点
尽管Protobuf在性能和效率方面具有明显优势,但它也有一些局限性。Protobuf的数据格式是二进制的,这使得它在调试和日志记录方面不如文本格式(如JSON)直观,增加了调试难度。同时,Protobuf的强类型定义要求在编译时就确定数据结构,这限制了其在需要动态字段处理的应用中的使用。此外,Protobuf的学习曲线相对较陡,需要开发者熟悉.proto文件的语法和protoc编译器的使用,这可能会增加开发和维护的复杂性。
使用指南
定义消息结构
首先,你需要定义一个或多个.proto文件,这些文件描述了你想要序列化的数据结构。.proto文件使用类似于IDL(接口定义语言)的语法。
proto
syntax = "proto3";message Person {string name = 1;int32 id = 2;string email = 3;
}
在这个例子中,我们定义了一个Person消息,包含三个字段:name、id和email。
- 编译.proto文件
使用protoc编译器生成对应语言的代码。例如,对于Java,命令可能如下:
sh
protoc --java_out=./output_directory person.proto
这将在指定的输出目录生成Java类文件。
-
包含Protobuf库
在你的项目中包含Protobuf库。对于不同的编程语言,这一步可能涉及添加依赖项、下载库文件或使用包管理器。 -
使用Protobuf API
在你的代码中,使用由protoc生成的类来创建、修改和访问消息。
java
Person person = Person.newBuilder().setName("John Doe").setId(1234).setEmail("john.doe@example.com").build();
- 序列化数据
将消息对象序列化为字节流,以便可以在网络上传输或存储到文件中。
java
byte[] data = person.toByteArray();
- 反序列化数据
从字节流中反序列化消息对象。
java
Person personFromBytes = Person.parseFrom(data);
- 处理消息
在你的应用程序中处理序列化和反序列化的消息。 - 管理版本
如果你需要修改.proto文件,确保以一种向后兼容的方式进行,以便旧版应用程序仍然可以处理新消息或忽略新字段。 - 调试和测试
使用Protobuf提供的工具进行调试和测试,确保序列化和反序列化过程按预期工作。
profobuf进行数据传输并结合Netty
先下载protobuf编译器 进行编译
并将其bin目录放在系统目录下面使用下面命令查看是否安装成功
轻松在java程序中使用protobuf详细介绍了生成的Java文件。
编写.proto文件
//定义版本
syntax = "proto3";
//生成的代码的类名和文件名
option java_outer_classname = "MessagePOJO";
//使用messae管理数据,注意名字不要和java_outer_classname冲突
message Message{//定义ID属性,int32对应java的,注意这里的1指的是需要而不是值int64 id = 1;//定义一个name属性,类型为字符串String,注意这里的2指的是需要而不是值string name = 2;//定义一个数组,爱好repeated string favorite = 3;
}
使用命令生成对应的java文件
令:protoc --java_out=目标地址 源地址/xxx.proto
protoc --java_out=src/main/java/protobuf src/main/java/protobuf/message.proto
然后生成的服务端代码
package protobuf;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;public class Client {public static void main(String[] args) throws InterruptedException {NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();Bootstrap bootstrap = new Bootstrap();bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//给客户端增加编码器,使用ProtobufEncoder编码器pipeline.addLast("encoder",new ProtobufEncoder());pipeline.addLast(new ClientHandler());}});try {ChannelFuture sync = bootstrap.connect("127.0.0.1", 8000).sync();sync.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();}finally {eventLoopGroup.shutdownGracefully();}}
}
package protobuf;import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;public class ClientHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//当建立连接,就发送一个对象给服务端MessagePOJO.Message message = MessagePOJO.Message.newBuilder().setId(1).setName("cs").build();ctx.writeAndFlush(message);System.out.println("客户端发送 user="+message.getName());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.channel().close();}
}
客户端代码
package protobuf;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;public class Server {public static void main(String[] args) {NioEventLoopGroup boss = new NioEventLoopGroup();NioEventLoopGroup work = new NioEventLoopGroup();try {ServerBootstrap bootstrap = new ServerBootstrap().group(boss, work).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();//服务端:使用protobuf解码器,需要指定解码器解码哪种类型pipeline.addLast("decoder", new ProtobufDecoder(MessagePOJO.Message.getDefaultInstance()));pipeline.addLast(new ServerHandler());}});ChannelFuture sync = bootstrap.bind(8000).sync();sync.channel().closeFuture().sync();} catch (InterruptedException e) {throw new RuntimeException(e);} finally {boss.shutdownGracefully();work.shutdownGracefully();}}
}
package protobuf;import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;public class ServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//把消息强转成UserPOJO.UserMessagePOJO.Message message = (MessagePOJO.Message) msg;System.out.println("拿到数据:"+message.getName());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.channel().close();}
}