【热门云产品免费试用活动】| 【最新活动】| 【企业应用优惠】
简介
Protobuf即Protocol Buffers,是Google公司开发的一种跨语言和平台的序列化数据结构的方式,是一个灵活的、高效的用于序列化数据的协议。与XML和JSON格式相比,Protobuf更小、更快、更便捷。
Protobuf是跨语言的,并且自带编译器(protoc),只需要用protoc进行编译,就可以编译成Java、Python、C++、C#、Go等多种语言代码,并可以直接使用。
编译安装方法
1.配置编译环境
安装wget工具。
yum install wget -y
2.获取源码
获取“protobuf-2.6.1”源码包。
cd /usr/local/src
wget https://github.com/protocolbuffers/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz
3.编译和安装
在CentOS 7.6以yum方式安装Protobuf,以及在EulerOS 2.8上以yum方式安装Protobuf请参见其他场景安装说明。
1)解压软件包。
cd /usr/local/src
tar -zxvf protobuf-2.6.1.tar.gz
2)进入Protobuf的安装目录。
cd protobuf-2.6.1/
3)安装Protobuf。
./configure --prefix=/usr/
make -j4 && make install
4)更新库。
ldconfig
----结束
4.运行和验证
1)创建测试源文件。
cd /usr/local/src
vi student.proto
在“student.proto”插入如下内容:
syntax = "proto2";
message Student {
optional string name = 1;
optional int32 age = 2;
}
2)编译和运行测试文件,将“student.proto”转化成c++源码。
protoc --cpp_out=./ ./student.proto
ll
回显内容如下,可发现已生成“student.pb.cc”和“student.pb.h”文件。
[root@ecs-protobuf-x src]# ll
total 2608
drwxr-xr-x 10 109965 5000 4096 Aug 17 16:29 protobuf-2.6.1
-rw-r--r-- 1 root root 2641426 May 21 2017 protobuf-2.6.1.tar.gz
-rw-r--r-- 1 root root 11400 Aug 17 16:40 student.pb.cc
-rw-r--r-- 1 root root 7554 Aug 17 16:40 student.pb.h
-rw-r--r-- 1 root root 97 Aug 17 16:40 student.proto
----结束
其他场景安装说明
在CentOS 7.6以yum方式安装Protobuf
由于CentOS 7.6的yum源中自带了Protobuf的RPM包,因此也可以采用yum直接安装。
安装方式如下:
yum install protobuf protobuf-devel -y
安装完成后,查看安装是否完成。
protoc --version
返回内容如下。
libprotoc 2.5.0
在EulerOS 2.8上以yum方式安装Protobuf
如果使用的OS是EulerOS 2.8,那么EulerOS yum源中自带了Protobuf的RPM包,采用yum直接安装。
a)安装Protobuf。
yum install protobuf protobuf-devel -y
安装完成后,查看安装是否完成。
protoc --version
返回内容如下。
libprotoc 3.5.0
b)创建测试源文件。
cd /usr/local/src
vi studetn.proto
在“student.proto”插入如下内容:
syntax = "proto3";
message Student {
string name = 1;
int32 age = 2;
}
由于Protobuf 3以及以上版本中默认的参数会自带optional标记,因此上述name和age的定义要去掉optional,否则会报如下错误:
“student.proto:3:13: Explicit 'optional' labels are disallowed in the Proto3 syntax. To define 'optional' fields in Proto3, simply remove the 'optional' label, as fields are 'optional' by default.”。
c)编译和运行测试文件,将“studetn.proto”转化成c++源码。
protoc --cpp_out=./ ./student.proto
ll
回显内容如下,可发现已生成“student.pb.cc”和“student.pb.h”文件。
[root@ecs-xyt ~]# protoc --cpp_out=./ student.proto
[root@ecs-xyt ~]# ll
total 32
-rw------- 1 root root 13980 Aug 17 17:07 student.pb.cc
-rw------- 1 root root 8501 Aug 17 17:07 student.pb.h
-rw------- 1 root root 85 Aug 17 16:45 student.proto
----结束
更多相关文章: