微服务学习(二)--protobuf

一、语法:

  syntax = "proto3";

  // 熊猫 发送消息
  message PandaRequest{
    // 姓名
    string name=1;
    // 身高
    int32 shengao=2;
    // 体重
    repeated int32 tizhong=3;
  }

  message PandaResponse{
    // 错误码
    int32 error=1;
    // 错误信息
    string message=2;
  }
二、数据类型

  A、double(float64)、float(float32)、int32、uint32、uint64、sint32(int32,使用变长编码,这些编码在负值时比int32高效的多)、sint64(int64,使用变长编码,编码时比通常的int64高效)、fixed32(uint32,总是4个字节,如果数值总是比228大的话,这个类型会比uint32高效)、fixed64(uint64,总是8个字节,如果数值总是比256大的话,会比uint64高效)、sfixed32(int32,总是4字节)、sfixed64(uint64,总是8字节)、bool、string、bytes([]byte,可能包含任意顺序的字节数据)

  B、使用其它消息类型

    message PersonInfo {

      repeated Person info=1;

    }

    message Person{

      string name=1;

      int32 shengao=2;

      repeated int32 tizhong=3;

    }

  C、嵌套类型

    1. message PersonInfo {

      message Person{

        string name=1;

        int32 shengao=2;

        repeated int32 tizhong=3

      }

      repeated Person info=1;

    }

    2. 在父消息外部重用

      message PersonMessage{

        PersonInfo.Person info=1;

      }

    3. 消息可以嵌套任意多层

三、定义服务(service)

  A、如果想要将消息类型用在RPC(远程方法调用)系统中,可以在.proto文件中定义一个RPC服务接口,protocol buffer编译器将会根据所选则的语言的不同生成服务代码及存根。如:

    service SearchService{

      // rpc 服务的函数名(传入参数)返回 (返回参数)

      rpc Search (SearchRequest) returns (SearchResponse)

    }

四、编译

  A、protoc --proto_path=IMPORT_PATH --cpp_out=DST_DIR --python_out=DST_DIR --go_out=DST_DIR path/to/file.proto

    IMPORT_PATH声明了一个.proto文件所在的解析import具体目录。如果忽略该值,则使用当前目录。如果有多个目录则可以多次调用--proto_path,它们将会顺序的被访问并导入。-I=IMPORT_PATH是--proto_path的简化形式。

猜你喜欢

转载自www.cnblogs.com/DjanFey/p/12157652.html