CentOS 执行 Protobuf 的步骤详解

什么是 Protobuf?
Protobuf(Protocol Buffers)是一种由 Google 开发的数据序列化格式,它可以将结构化数据序列化为紧凑的二进制格式,便于存储和传输,Protobuf 支持多种编程语言,包括 C++、Java、Python 等,这使得它在分布式系统中被广泛使用。
在 CentOS 上安装 Protobuf
安装依赖
在 CentOS 上安装 Protobuf 之前,需要确保系统已安装以下依赖:
sudo yum install -y autoconf automake libtool python3 python3-pip
安装 protobuf
使用以下命令安装 protobuf:
sudo yum install -y protobuf protobuf-compiler
安装 protobuf 的 Python 库

sudo pip3 install protobuf
创建 Protobuf 文件
- 创建
.proto文件
在项目目录下创建一个 .proto 文件,example.proto,并定义你的数据结构:
syntax = "proto3";
message Person {
string name = 1;
int32 id = 2;
string email = 3;
} - 使用
protoc编译.proto文件
在命令行中,使用以下命令编译 .proto 文件:
protoc --python_out=. example.proto
这将生成一个名为 example_pb2.py 的 Python 文件,其中包含了 Person 类的定义。
使用 Protobuf 在 Python 中序列化和反序列化数据
导入生成的 Python 文件
在 Python 代码中,导入生成的 example_pb2.py 文件:
from example_pb2 import Person
创建 Protobuf 对象

person = Person(name="John Doe", id=123, email="john.doe@example.com")
序列化 Protobuf 对象
person_bytes = person.SerializeToString()
反序列化 Protobuf 字节流
person_parsed = Person() person_parsed.ParseFromString(person_bytes) print(person_parsed.name)
FAQs
问题 1:如何查看 Protobuf 的版本信息?
解答:在命令行中,使用以下命令查看 protobuf 的版本信息:
protoc --version
问题 2:在 CentOS 上安装 protobuf 时遇到依赖问题怎么办?
解答:遇到依赖问题时,可以尝试以下步骤:
- 检查是否已安装所有必要的依赖,如
autoconf,automake,libtool,python3,python3-pip。 - 使用
sudo yum install -y <dependency>命令安装缺失的依赖。 - 如果问题仍然存在,可以尝试更新
yum缓存并重新安装 protobuf:
sudo yum clean all sudo yum makecache sudo yum install -y protobuf protobuf-compiler

