go版本protobuf 在windows系统下安装环境

1.下载protobuf的编译器protoc
访问https://github.com/google/protobuf/releases
下载这里写图片描述
下载解压出protoc.exe文件放入gopath下的bin目录;
2.下载protobuf编译器所需插件
用git下载protoc在go下运行所需插件(执行): go get github.com/golang/protobuf(gopath的bin目录会生成protoc-gen-go.exe),
此时在gopath的bin目录下你会看到:
这里写图片描述
然后将gopath的bin目录加到环境变量里,protobuf搭建完毕。
3、编写.proto文件,然后生成.go文件
1>:运行方法protoc xx.proto - -go_out=. (只调用protoc生成文件序列化和反序列化的代码,不能生成服务器和客户端通讯方法,即server方法);
2>:或者在当前目录下 protoc –go_out=plugins=grpc,import_path=mypackage:. *.proto(会调用rotoc-gen-go 除生成文件序列号和反序列化代码,也会生成server服务器和客户端通讯方法。)
例子:
书写protobuf文件:

//protobuf 语法版本
syntax = "proto3";
package services;
//远程过程调用的通讯方法
service RegisterService {
    rpc GetStatus (StatusRequest) returns (StatusResponse) {}
    rpc GetCode (CodeRequest) returns (CodeResponse) {}
}
//message 代表数据类型,比如上边两个通讯服务的参数和返回结果的类型
message CodeRequest{
}
message CodeResponse {
    string code = 1; //1 代表该字段的代号,不能重复
}
message StatusRequest {
}
message StatusResponse {
    AppData appData = 1;
}
message AppData {
    int32 counter = 1;
    map<string, string> attendants = 2;
}
message Attendant {
    string firstName = 1;
    string lastName = 2;
    string code = 3;
}

在当前目录执行:
这里写图片描述
即可生成go文件:
这里写图片描述
另外需要注意的是protobuf 对string和byte是不压缩的,在string较大时,需要考虑进行压缩,protobuf 本身预留了字符串传入压缩接口。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章