美文网首页
初识protobuf go语言版

初识protobuf go语言版

作者: mafa1993 | 来源:发表于2021-08-24 21:13 被阅读0次

protobuf

一种二进制传输数据包

  1. go的protobuf包
    • go get github.com/golang/protobuf/proto
    • go get google.golang.org/grpc
    • go get github.com/golang/protobuf/protoc-gen-go
  2. 需要protoc编译文件 https://github.com/protocolbuffers/protobuf/releases,并添加环境变量(或者放到GOPATH的bin目录下)。使用命令 protoc
    • protoc -I . --go_out=plugins=grpc:. ./goods.proto
    • 在windows环境下测试有问题,后再linux使用无问题
The import path must contain at least one forward slash ('/') character.

protos文件里定义的 option 必须包含一个斜杠

protobuf的优缺点

  1. 利用protoc解析器将.proto文件解析成相应文件 good.proto => goods.pd.go
  2. 引入生成的go文件。进行服务调用与通信
  3. pb.go封装了数据,二进制数据
  4. 量级小(json的1/5,xml的1/20),解析块,向下兼容好
  5. 通用箱稍差,人不可读,安全性高

protobuf和go转换

  1. 会针对每个message生成几个方法
syntax = "proto3";   // 定义版本,默认为proto2

package user;  // go 包名

option go_package = "./user"; // 如果和package不一致,会使用下面这个,一般会协程.:user 因为路径问题会报错, 新版protoc要求这个定义至少有个/

message User { //定义消息的额格式,
    int32 id = 1; // 无int类型,只用int32
    string name = 2;
    int32 age = 3;

    Role role = 4;

    map<string,string> dict = 5;  //map类型

    message Role {    // 可以嵌套书写,相当于 type type User_Role struct{}
        int32 id = 1;
        string role_name = 2;

        Status status = 3;

        enum Status {  // 枚举类型  岘港与go中的常量
            OK = 0;
            FAIL = 1;
        }
    }
}

// service 相当于go中的接口
// type UserService interface{ Auth(User) Response}
service UserService {
    rpc Auth(User) returns (Response){}  // rpc方式,调动Auth方法,返回值时Response  Auth的参数和returns的参数不能为空
    // rpc 方法名(参数 使用message定义) returns(message 定义 返回的类型)
}

message Response{
    string code = 1;
    string token = 2;
    User user = 3;
}

相关文章

网友评论

      本文标题:初识protobuf go语言版

      本文链接:https://www.haomeiwen.com/subject/fnrjiltx.html