1. 程式人生 > >go版本protobuf 在windows系統下安裝環境

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