Protocol Buffer 学习笔记

本文由 gpt-4.1 生成,并进行少量修改。

基本结构

一个 .proto 文件通常包含如下部分:

syntax = "proto3";

package mypackage;

service MyService {
  // 服务定义
}

message MyMessage {
  // 字段定义
}
  • syntax = "proto3";:指定语法版本,推荐使用 proto3。
  • package mypackage;:指定包名,防止命名冲突。

消息类型

消息(message)用于定义数据结构,相当于面向对象编程中的类。例如:

message Person {
  string name = 1;
  int32 id = 2;
  bool is_student = 3;
}
  • 字段类型:如 string、int32、bool 等。
  • 字段名:如 name、id、is_student。
  • 字段编号:如 1、2、3。每个字段必须有唯一编号,序列化时用编号而不是名字。

基本数据类型

常用的 proto3 数据类型:

  • double, float
  • int32, int64, uint32, uint64, sint32, sint64, fixed32, fixed64, sfixed32, sfixed64
  • bool
  • string
  • bytes

枚举类型

枚举(enum)用于定义一组命名常量:

enum Gender {
  UNKNOWN = 0;
  MALE = 1;
  FEMALE = 2;
}

嵌套消息

消息类型可以嵌套定义:

message Student {
  string name = 1;
  message Score {
    string subject = 1;
    int32 value = 2;
  }
  Score score = 2;
}

重复字段

重复字段(repeated)用于定义数组或列表:

message Group {
  repeated string members = 1;
}

Map 类型

用于定义键值对:

message Dict {
  map<string, int32> items = 1;
}

服务定义

服务(service)用于 gRPC 等 RPC 场景:

service MyService {
  rpc MyMethod (MyRequest) returns (MyResponse);
}
  • service MyService:定义一个名为 MyService 的服务。

  • rpc MyMethod (MyRequest) returns (MyResponse):在 MyService 服务中定义一个名为 MyMethod 的远程过程调用(RPC)方法。

    • MyMethod:方法名。
    • MyRequest:请求消息类型,表示客户端发送给服务器的数据结构。
    • MyResponse:响应消息类型,表示服务器返回给客户端的数据结构。
  • message HelloRequest:定义了一个消息类型 HelloRequest。

  • string name = 1;:消息中包含一个名为 name 的字符串字段,字段编号为 1(protobuf 要求每个字段有唯一编号)。

注释

  • 单行注释://
  • 多行注释:/* ... */

其他

  • import:引入其他 proto 文件

    import "other.proto";
    
  • option:设置编译选项

    option java_package = "com.example.foo";
    

编译

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

参见:Language Guide (proto 3) | Protocol Buffers Documentation

posted @ 2025-06-29 00:22  Undefined443  阅读(14)  评论(0)    收藏  举报