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 本身預留了字符串傳入壓縮接口。