使用 protobuf

1. 什么是 Protocol Buffers

Protocol Buffers(简称 protobuf)是 Google 开发的一种语言中立、平台无关、可扩展的结构化数据序列化协议,常用于网络通信和数据存储。

特点:

  • 体积小、效率高(相比 JSON 更快更紧凑)
  • 支持多语言生成代码
  • 可向后兼容字段修改

2. 定义 .proto 文件

一个简单的 protobuf 文件示例:

syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
  repeated string hobbies = 3;
}

说明:

  • syntax = "proto3":指定语法版本
  • message:定义结构体类型
  • 字段编号用于序列化顺序,不能重复

3. 安装 protoc 与插件

go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

确保 GOPATH/bin 在环境变量中。

4. 生成 Go 代码

使用 protoc 编译:

protoc --go_out=. --go_opt=paths=source_relative \
       --go-grpc_out=. --go-grpc_opt=paths=source_relative \
       person.proto

将生成对应的 .pb.go 文件。

5. 在 Go 中使用

使用生成的结构体:

p := &Person{
    Name: "Alice",
    Age:  30,
    Hobbies: []string{"reading", "cycling"},
}

data, err := proto.Marshal(p)
var p2 Person
err = proto.Unmarshal(data, &p2)

protobuf 是构建高效、高性能通信接口的核心工具,特别适用于 gRPC 和跨语言系统开发。