欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

google protobuf 对象转字节码 博客分类: Java  

程序员文章站 2024-03-19 10:33:52
...

1、开源地址:

https://github.com/google/protobuf/

2、发布版本下载:

https://github.com/google/protobuf/releases

 

3、什么是Protobuf

官方文档给出的是:

 

a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more.

 

3、数据类型

 

.proto

 

 

 

Type

Notes C++ Type Java Type
double    double  double
float    float  float
int32 Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.  int32  int
int64 Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead.  int64  long
uint32 Uses variable-length encoding.  uint32  int
uint64 Uses variable-length encoding.  uint64  long
sint32 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.  int32  int
sint64 Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s.   int64  long
fixed32 Always four bytes. More efficient than uint32 if values are often greater than 228  uint32  int
fixed64 Always eight bytes. More efficient than uint64 if values are often greater than 256.  uint64  long
sfixed32 Always four bytes.  int32  int
sfixed64 Always eight bytes.  int64  long
bool    bool  boolean
string A string must always contain UTF-8 encoded or 7-bit ASCII text.  string  String
bytes May contain any arbitrary sequence of bytes. string ByteString

  

 

 5、Protobuf的优点

1、性能好,效率高

2、代码生成机制,数据解析类自动生成

3、支持向后兼容和向前兼容

4、支持多种编程语言(java,c++,python)

 

6、Protobuf的缺点

1、应用不够广

2、二进制格式导致可读性差(二进制格式)

3、缺乏自描述

 

7、Protobuf环境的搭建

根据不同操作系统下载不同的发布版本

https://github.com/google/protobuf/releases,

 

8、新建第一个proto文件

文件名为:ResponseMsg.proto

option java_package = "io.hpgary.netty.pb"; //生成java的包名
option java_outer_classname = "ResponseMsgProbuf"; // 生成java的类名
  
message  ResponseMsg {
    required bytes response = 1;
}

9、转换成为java类:

使用命令:

# ../java 是源代码所在目录
protoc.exe --java_out ../java ResponseMsg.proto

 

10、使用:

ByteString byteString = ByteString.copyFrom("aaa".getBytes());
RequestMsg.Builder requstMsg = RequestMsg.newBuilder();
requstMsg.setCmd("hp_call");
requstMsg.setRequestParam( byteString );