一.protobuf簡介
前言
在移動(dòng)互聯(lián)網(wǎng)時(shí)代, 手機(jī)流量、 電量是最為有限的資源,而移動(dòng)端的即時(shí)通訊應(yīng)用無疑必須得直面這兩點(diǎn)。解決流量過大的基本方法就是 使用高度壓縮的通信協(xié)議,而數(shù)據(jù)壓縮后流量減小帶來的自然結(jié)果也就是省電:因?yàn)榇髷?shù)據(jù)量的傳輸必然需要 更久的網(wǎng)絡(luò)操作、 數(shù)據(jù)序列化及 反序列化操作,這些都是電量消耗過快的根源。當(dāng)前即時(shí)通訊應(yīng)用中最熱門的 通信協(xié)議無疑就是 Google的Protobuf了,基于它的優(yōu)秀表現(xiàn), 微信和手機(jī)QQ這樣的主流IM應(yīng)用也早已在使用它
簡介
Protobuf是 Protocol Bu?ers的簡稱,它是Google公司開發(fā)的一種 數(shù)據(jù)描述語言,是一種 輕便高效的 結(jié)構(gòu)化數(shù)據(jù)存儲(chǔ)格式,可以 用于結(jié)構(gòu)化數(shù)據(jù),或者說 序列化,它很適合做 數(shù)據(jù)存儲(chǔ)或 RPC 數(shù)據(jù)交換格式,可用于 通訊協(xié)議、 數(shù)據(jù)存儲(chǔ)等領(lǐng)域的語言無關(guān)、平臺(tái)無關(guān)、可擴(kuò)展的 序列化結(jié)構(gòu)數(shù)據(jù)格式,是一種 靈活, 高效, 自動(dòng)化的機(jī)制,用于 序列化結(jié)構(gòu)化數(shù)據(jù),對(duì)比于 XML和JSON,它 更小、更快、 更簡單,總之它是 微服務(wù)中需要使用的東西. 目前提供了 C++、Java、Python 三種語言的 API(即時(shí)通訊網(wǎng)注:Protobuf官方工程主頁上顯示的已支持的開發(fā)語言多達(dá)10種,分別有:C++、Java、Python、Objective-C、C#、JavaNano、JavaScript、Ruby、Go、PHP,基本上主流的語言都已支持).
Protobuf剛開源時(shí)的定位類似于XML、JSON等數(shù)據(jù)描述語言,通過 附帶工具生成代碼并 實(shí)現(xiàn)將結(jié)構(gòu)化數(shù)據(jù)序列化的功能.這里更關(guān)注的是Protobuf作為 接口規(guī)范的描述語言,可以 作為設(shè)計(jì)安全的跨語言RPC接口的基礎(chǔ)工具

需要了解幾點(diǎn)
protobuf是類似與json一樣的數(shù)據(jù)描述語言(數(shù)據(jù)格式)
protobuf非常適合于RPC數(shù)據(jù)交換格式
序列化:將數(shù)據(jù)結(jié)構(gòu)或?qū)ο筠D(zhuǎn)換成二進(jìn)制串的過程
反序列化:將在序列化過程中所產(chǎn)生的二進(jìn)制串轉(zhuǎn)換成數(shù)據(jù)結(jié)構(gòu)或對(duì)象的過程
protobuf的優(yōu)勢(shì)和劣勢(shì)
(1).優(yōu)勢(shì)
序列化后體積相比Json和XML很小,適合網(wǎng)絡(luò)傳輸
支持跨平臺(tái)多語言
消息格式升級(jí)和兼容性很好,不必破壞舊的數(shù)據(jù)格式,就能對(duì)數(shù)據(jù)結(jié)構(gòu)進(jìn)行更新
序列化反序列化速度很快,快于Json的處理速度
跨平臺(tái)、跨語言、可擴(kuò)展性強(qiáng)
維護(hù)成本低,多平臺(tái)只需要維護(hù)一套對(duì)象協(xié)議文件,即.proto文件
加密性好,http傳輸內(nèi)容抓包只能抓到字節(jié)數(shù)據(jù)
(2).劣勢(shì)
應(yīng)用不夠廣(相比xml和json)
二進(jìn)制格式導(dǎo)致可讀性差
缺乏自描述
二.protobuf的安裝
windows電腦上面安裝protocol bu?ers
github地址: https://github.com/protocolbuffers/protobuf
版本下載地址: https://github.com/protocolbuffers/protobuf/tags
(1).下載
這里下載protobuf v3.15.5 的版本,下載地址: https://github.com/protocolbuffers/protobuf/releases/tag/v3.15.5,選擇 protoc-3.15.5-win64.zip 下載,減壓并將解壓得到的文件中的bin目錄路徑添加到系統(tǒng)變量中
1).官網(wǎng)下載

2).解壓

3).添加到環(huán)境變量
環(huán)境變量添加操作見文檔: 安裝ElasticSearch之前的準(zhǔn)備工作jdk的安裝
在 系統(tǒng)變量找到Path ,把 bin目錄路徑添加 ,然后完成就可以了


4).重啟計(jì)算機(jī)
配置了環(huán)境變量,為了使其生效,需要重啟計(jì)算機(jī)
(2).查看版本
出現(xiàn)以下顯示,說明protobuf 安裝成功

(3).protobuf的go語言插件protoc-gen-go插件
go install github.com/golang/protobuf/protoc-gen-go@latest
安裝結(jié)果如下:
F:\www\go-data\src\go_code\micro>go install github.com/golang/protobuf/protoc-gen-go@latest
go: downloading github.com/golang/protobuf v1.5.3
go: downloading google.golang.org/protobuf v1.26.0
F:\www\go-data\src\go_code\micro>
Mac電腦上面安裝protocol bu?ers
Linux和Mac安裝方式類似
(1).方式一:安裝protobuf (推薦)
如果電腦上面沒有brew先安裝brew
brew install protobuf
(2).方式二:安裝protobuf
如果電腦沒有安裝brew也可以使用下面方法安裝
(1).下載
下載地址: https://github.com/protocolbu%EF%AC%80ers/protobuf/releases
選擇適合macos的protobuf,比如選擇protoc-3.12.1-osx-x86_64.zip
(2).解壓
解壓包得到protoc-3.12.1-osx-x86_64
(3).重命名
mv protoc-3.12.1-osx-x86_64 protobuf
(4).配置環(huán)境變量
vim ~/.bash_profile
export PROTOBUF=/Users/nacos/Library/protobuf
export PATH=$PATH:$PROTOBUF/bin
(5).刷新配置
source ~/.bash_profile
(6).查看版本
protoc --version
(3).protobuf的go語言插件protoc-gen-go插件
go install github.com/golang/protobuf/protoc-gen-go@latest
(4).配置環(huán)境變量
安裝完畢后如果提示 沒法使用protoc-gen-go,還需要把 gopath對(duì)應(yīng)的bin目錄配置到環(huán)境變量
vim ~/.bash_profile
export PATH=/Users/nacos/go/bin:$PATH
(5).刷新配置
配置完保存記得刷新下配置
source ~/.bash_profile
測(cè)試protoc和protoc-gen-go是否全部配置成功
(1).新建 test.proto
syntax = "proto3";
option go_package = "./protoService";
message Userinfo {
string name = 1;
int32 age = 2;
repeated string hobby = 3;
}
(2).把proto 文件編譯成go文件
F:\www\go-data\src\go_code\micro\protoc>protoc --go_out=./ *.proto
(3).結(jié)果
運(yùn)行以上命令后,正確的結(jié)果如下:

三.protobuf 的用法
參考文檔(需科學(xué)上網(wǎng)): https://developers.google.com/protocol-buffers/docs/proto3
protobuf 簡單語法
(1).案例引入
先看代碼,然后根據(jù)代碼講解,創(chuàng)建一個(gè)后綴為.proto的protobuf語法的文件,如下:
syntax = "proto3"; //指定版本信息,不指定會(huì)報(bào)錯(cuò),默認(rèn)是proto2
//分號(hào)(;)前面的表示當(dāng)前.proto文件所在的路徑,分號(hào)后面表示生成go文件的包名
option go_package = "./proto;helloworld";
//message定義一種消息類型,關(guān)鍵字message定義結(jié)構(gòu),并且結(jié)構(gòu)中可以嵌套定義結(jié)構(gòu),message定義的內(nèi)容和生成一個(gè)結(jié)構(gòu)體
message Person{
? ? //名字
? ? string name = 1;
? ? //年齡
? ? int32 age = 2 ;
? ? //愛好
? ? repeated string hobby = 3; // repeadted關(guān)鍵字類似與go中的切片,編譯之后對(duì)應(yīng)的也是go的切片,golang中會(huì)生成string類型的切片
}
(2).總結(jié)
protobuf消息的定義(或者稱為描述)通常都寫在一個(gè)以 .proto 結(jié)尾的文件中
該文件的第一行指定正在使用 proto3 語法:如果不這樣做,協(xié)議緩沖區(qū)編譯器將假定正在使用proto2,這也必須是文件的第一個(gè)非空的非注釋行
第二行 option go_package 指定生成go文件的目錄以及包名稱
最后message關(guān)鍵字定義一個(gè)Person消息體,類似于go語言中的結(jié)構(gòu)體,是包含一系列類型數(shù)據(jù)的集合,許多標(biāo)準(zhǔn)的簡單數(shù)據(jù)類型都可以作為字段類型,包括 bool , int32 ,float , double ,和 string 。也可以使用其他message類型作為字段類型
在message中有一個(gè)字符串類型的value成員,該成員編碼時(shí)用1代替名字,在json中是通過成員的名字來綁定對(duì)應(yīng)的數(shù)據(jù),但是Protobuf編碼卻是通過成員的唯一編號(hào)來綁定對(duì)應(yīng)的數(shù)據(jù),因此Protobuf編碼后數(shù)據(jù)的體積會(huì)比較小,能夠快速傳輸,缺點(diǎn)是不利于閱讀
(3).message的格式說明
消息由 至少一個(gè)字段組合而成,類似于Go語言中的 結(jié)構(gòu)體,每個(gè)字段都有一定的格式:
//注釋格式 注釋盡量也寫在內(nèi)容上方
(字段修飾符)數(shù)據(jù)類型 字段名稱 = 唯一的編號(hào)標(biāo)簽值;
唯一的編號(hào)標(biāo)簽:代表每個(gè)字段的一個(gè)唯一的編號(hào)標(biāo)簽,在同一個(gè)消息里不可以重復(fù),這些編號(hào)標(biāo)簽用與在消息二進(jìn)制格式中標(biāo)識(shí)字段,并且消息一旦定義就不能更改,需要說明的是標(biāo)簽在1到15范圍的采用一個(gè)字節(jié)進(jìn)行編碼,16 ~ 2047采用雙字節(jié)編碼,所以通常將標(biāo)簽1到15用于頻繁發(fā)生的消息字段,編號(hào)標(biāo)簽大小的范圍是1到2的29次,19000-19999是官方預(yù)留的值,不能使用
注釋格式:向.proto文件添加注釋,可以使用C/C++/java/Go風(fēng)格的雙斜杠(//) 語法格式或者 /*.....*/
可以在單個(gè).proto中定義多種消息類型,如果要定義多個(gè)相關(guān)消息,這很有用——例如,如果想定義與搜索響應(yīng)消息類型相對(duì)應(yīng)的回復(fù)消息格式,可以將其添加到該.proto中
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}
message SearchResponse {
...
}
message常見的數(shù)據(jù)類型與go中類型對(duì)比


(4).proto2和proto3差別
proto3 比 proto2 支持更多語言但 更簡潔,去掉了一些復(fù)雜的語法和特性,更 強(qiáng)調(diào)約定而 弱化語法
區(qū)別
在第一行非空白非注釋行,必須寫:syntax = “proto3”
字段規(guī)則移除了 “required”,并把 “optional” 改名為 “singular”
proto3 repeated標(biāo)量數(shù)值類型默認(rèn)packed,而proto2默認(rèn)不開啟
在 proto2 中,需要明確使用 [packed=true] 來為字段指定比較緊湊的 packed 編碼方式
語言增加 Go、Ruby、JavaNano 支持
proto2可以選填default,而proto3只能使用系統(tǒng)默認(rèn)的
在 proto2 中,可以使用 default 選項(xiàng)為某一字段指定默認(rèn)值, 在 proto3 中,字段的默認(rèn)值只能根據(jù)字段類型由系統(tǒng)決定,也就是說, 默認(rèn)值全部是約定好的,而不再提供指定默認(rèn)值的語法
proto3必須有一個(gè)零值,以便可以使用 0 作為數(shù)字默認(rèn)值,零值需要是第一個(gè)元素,以便與proto2語義兼容,其中第一個(gè)枚舉值始終是默認(rèn)值,proto2則沒有這項(xiàng)要求
proto3在3.5版本之前會(huì)丟棄未知字段,但在 3.5 版本中,重新引入了未知字段的保留以匹配 proto2 行為,在 3.5 及更高版本中,未知字段在解析過程中保留并包含在序列化輸出中
proto3移除了proto2的擴(kuò)展,新增了Any(仍在開發(fā)中)和JSON映射
proto3字段規(guī)則
singular: 可以有零個(gè)或其中一個(gè)字段(但不超過一個(gè))
repeated: 該字段可以重復(fù)任意次數(shù)(包括零次),重復(fù)值的順序?qū)⒈槐A?/p>
在proto 3中,可擴(kuò)展的repeated字段為數(shù)字類型的默認(rèn)編碼
在proto2中,規(guī)則為:
required:必須有一個(gè)
optional:0或者1個(gè)
repeated:任意數(shù)量(包括0)
protobuf高級(jí)用法
(1).message嵌套
messsage除了能放 簡單數(shù)據(jù)類型外,還能存放 另外的message類型,如下:
syntax = "proto3";//指定版本信息,不指定會(huì)報(bào)錯(cuò)
option go_package = "./proto;helloworld";
//message為關(guān)鍵字,作用為定義一種消息類型
message Person{
? ? //名字
? ? string name = 1;
? ? //年齡
? ? int32 age = 2 ;
? ? //定義一個(gè)message
? ? message PhoneNumber {
? ? ? ? string number = 1;
? ? ? ? int64 type = 2;
? ? }
? ? PhoneNumber phone = 3;
}
(2).repeated關(guān)鍵字
repeadted關(guān)鍵字類似與 go中的切片,編譯之后對(duì)應(yīng)的也是go的切片,用法如下
syntax = "proto3";//指定版本信息,不指定會(huì)報(bào)錯(cuò)
option go_package = "./proto;helloworld";
//message為關(guān)鍵字,作用為定義一種消息類型
message Person{
? ? //名字 ?
? ? string name = 1;
? ? //年齡? ?
? ? int32 age = 2 ;
? ? //定義一個(gè)message
? ? message PhoneNumber {
? ? ? ? string number = 1;
? ? ? ? int64 type = 2;
? ? }
? ? // repeated: 該字段可以重復(fù)任意次數(shù)(包括零次)。重復(fù)值的順序?qū)⒈槐A?? ? repeated PhoneNumber phone = 3;
}
(3).默認(rèn)值
當(dāng)解析 message 時(shí),如果被編碼的 message 里沒有包含某些變量,那么根據(jù)類型不同,他們會(huì)有不同的默認(rèn)值,具體如下:
string:默認(rèn)是空的字符串
byte:默認(rèn)是空的bytes
bool:默認(rèn)為false
numeric:默認(rèn)為0
enums:默認(rèn)值是第一個(gè)定義的枚舉值,該值必須為0
repeated字段默認(rèn)值是空列表
message字段的默認(rèn)值為空對(duì)象
收到數(shù)據(jù)后反序列化后,對(duì)于 標(biāo)準(zhǔn)值類型的數(shù)據(jù),比如bool,如果它的值是 false,那么就無法判斷這個(gè)值是對(duì)方設(shè)置的,還是對(duì)方壓根就沒給這個(gè)變量設(shè)置值
(4).enum關(guān)鍵字
在定義消息類型時(shí),可能會(huì)希望其中一個(gè)字段有一個(gè) 預(yù)定義的值列表,比如說,電話號(hào)碼字段有個(gè)類型,這個(gè)類型可以是:home,work,mobile,可以通過enum在消息定義中添加每個(gè)可能值的常量來非常簡單的執(zhí)行此操作,實(shí)例如下
syntax = "proto3";//指定版本信息,不指定會(huì)報(bào)錯(cuò)
package pb;//后期生成go文件的包名
//message為關(guān)鍵字,作用為定義一種消息類型
message Person{? ?
? ? //名字
? ? string name = 1;
? ? //年齡
? ? int32?age = 2 ;
? ? //定義一個(gè)message
? ? message PhoneNumber {
? ?? ? string number = 1;
? ? ? ? PhoneType type = 2;
? ? }
? ? repeated PhoneNumber phone = 3;
// 枚舉:可以在message內(nèi)定義
? ? enum Corpus {
UNIVERSAL = 0;
WEB = 1;
IMAGES = 2;
LOCAL = 3;
NEWS = 4;
PRODUCTS = 5;
VIDEO = 6;
}
Corpus corpus = 4;
}
//enum為關(guān)鍵字,作用為定義一種枚舉類型,可以在message外定義
enum PhoneType {
? ? MOBILE = 0;
? ? HOME = 1;
? ? WORK = 2;
}
如上,enum的 第一個(gè)常量映射為0,每個(gè)枚舉定義 必須包含一個(gè)映射到零的常量作為其 第一個(gè)元素,這是因?yàn)椋?
必須有一個(gè)零值,以便可以使用0作為數(shù)字 默認(rèn)值
零值必須是第一個(gè)元素,以便與proto2語義 兼容,其中第一個(gè)枚舉值始終是默認(rèn)值
枚舉值不能重復(fù),除非使用 option allow_alias = true 選項(xiàng)來開啟別名:
enum EnumAllowingAlias {
option allow_alias = true;
UNKNOWN = 0;
STARTED = 1;
RUNNING = 1;.
}
枚舉定義在一 個(gè)消息內(nèi)部或消息外部都是可以的,如果枚舉是 定義在 message 內(nèi)部,而其他message又想使用,那么可以通過 MessageType.EnumType 的方式引用
(5).定義RPC服務(wù)
如果需要將message與 RPC一起使用,則可以在 .proto 文件中 定義RPC服務(wù)接口,protobuf編譯器將根據(jù)選擇的語言生成RPC接口代碼,示例如下:
//定義RPC服務(wù)
service HelloService {
? ? rpc Hello (Person)returns (Person);
}
定義一個(gè)RPC的服務(wù)
syntax = "proto3";
option go_package = "./sayService";
service sayService {
? ? rpc SayHello(HelloRequest) returns (HelloRes)
}
message HelloRequest {
? ? string name = 1;
}
message HelloRes {
? ? string message = 1;
}
生成go文件命令:
生成 帶RPC服務(wù)相關(guān)的需要使用以下命令
protoc --go_out=plugins=grpc:. *.proto
(6).案例總結(jié)
syntax = "proto3";
//聲明是為了防止不同項(xiàng)目之間的命名沖突,編譯生成的類將被放置在一個(gè)與 package 名相同的命名空間中
package tutorial;
message Student {
// 字段編號(hào):消息定義中的每個(gè)字段都有一個(gè)唯一的編號(hào),這些字段編號(hào)用于以二進(jìn)制格式標(biāo)識(shí)您的字段,一旦您的消息類型被使用,就不應(yīng)該被更改
uint64 id = 1;
string name = 2;
// singular修飾符修飾的字段可以是0次或者1次,但是當(dāng)定制協(xié)議,用該修飾符修飾的字段都報(bào)錯(cuò)
// singular string email = 3;
string email = 3;
enum PhoneType {
MOBILE = 0; //proto3版本中,首成員必須為0,成員不應(yīng)有相同的值
HOME = 1;
}
message PhoneNumber {
string number = 1;
PhoneType type = 2;
}
// repeated: 該字段可以重復(fù)任意次數(shù)(包括零次),重復(fù)值的順序?qū)⒈槐A? repeated PhoneNumber phone = 4;
}
protobuf基本編譯
protobuf 編譯是通過 編譯器protoc進(jìn)行的,通過這個(gè)編譯器,可以把.proto文件生成
go,Java,Python,C++, Ruby, JavaNano, Objective-C,或者C# 代碼,生成命令如下:
protoc --proto_path= IMPORT_PATH --go_out= DST_DIR path/to/file.proto
--proto_path=IMPORT_PATH,IMPORT_PATH是 .proto 文件所在的路徑,如果忽略則默認(rèn)當(dāng)前目錄,如果有多個(gè)目錄則可以多次調(diào)用--proto_path,它們將會(huì)順序的被訪問并執(zhí)行導(dǎo)入
--go_out=DST_DIR, 指定了生成的go語言代碼文件放入的文件夾
允許使用 protoc --go_out=./ *.proto 的方式一次性編譯多個(gè) .proto 文件
go語言編譯時(shí),protobuf 編譯器會(huì)把 .proto 文件編譯成 .pd.go 文件
一般在使用的時(shí)候都是使用下面這種簡單的命令
protoc --go_out=./ *.proto
然后給這個(gè) .proto 文件中添加一個(gè)RPC服務(wù),再次進(jìn)行編譯,發(fā)現(xiàn)生成的go文件沒有發(fā)生變化,這是因?yàn)槭澜缟系腞PC實(shí)現(xiàn)有很多種,protoc編譯器并不知道該如何為HelloService服務(wù)生成代碼,不過在protoc-gen-go內(nèi)部已經(jīng)集成了一個(gè)叫grpc的插件,可以針對(duì)grpc生成代碼:
protoc --go_out=plugins=grpc:. *.proto
protobuf 序列化反序列化
(1).新建proto/test.proto
syntax = "proto3";
option go_package = "./protoService";
message Userinfo {
string name = 1;
int32 age = 2;
repeated string hobby = 3;
PhoneType phone=4;
}
//enum為關(guān)鍵字,作用為定義一種枚舉類型
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
(2).命令運(yùn)行,生成.go文件
protoc --go_out=./ *.proto //一般情況下使用這個(gè)命令
protoc --go_out=plugins=grpc:. *.proto //有RPC服務(wù)的情況下使用這個(gè)命令
生成的.go文件如下圖所示:

在這里使用了google.golang.org/protobuf下相關(guān)函數(shù),則需要引入對(duì)應(yīng)的插件進(jìn)行操作,命令如下:

如果protoService/test.pd.go中的protobuf還是沒有被引入,圖示:

則找到go mod tidy 下載的google.golang.org,把protobuf復(fù)制到src下,如圖示:


這樣protoServe/test.pb.go中的goole相關(guān)插件就引入了,test.pb.go中的protobuf變綠,成功了:

main.go中實(shí)現(xiàn)序列化和反序列化
package main
import (
"fmt"
"go_code/micro/protoc/protoService"
"google.golang.org/protobuf/proto"
)
func main() {
? ? //初始化并賦值
u := &protoService.Userinfo{
Name: "zhangsan",
Age: 20,
Hobby: []string{"吃飯", "睡覺", "寫代碼"},
}
fmt.Println(u.GetHobby())
// proto.Marshald對(duì)protoBufer進(jìn)行序列化
data, err1 := proto.Marshal(u)
if err1 != nil {
fmt.Println(err1)
}
fmt.Println(data)
//proto.Unmarshal可以對(duì)protoBufer進(jìn)行反序列化
info := protoService.Userinfo{}
err2 := proto.Unmarshal(data, &info)
if err2 != nil {
fmt.Println(err2)
}
fmt.Printf("%#v", info)
fmt.Println(info.GetHobby())
}
效果如下圖所示:

protobuf案例演示
(1).案例1
userinfo.proto
用戶信息相關(guān)proto:
使用了數(shù)據(jù)類型 string, int, repeated,enum等
syntax = "proto3"; //版本
//./userService:在./userService文件夾中生成文件
option go_package = "./userService";
//注意:寫完一行以后要注意 ;
message userinfo{
string username =1; //類型 字段 = 數(shù)字(位置)
int32 age =2;
PhoneType type=3;
repeated string hobby=4;
}
//enum為關(guān)鍵字,作用為定義一種枚舉類型
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
//編譯的命令:protoc --go_out=./ *.proto
userService/userinfo.pd.go
使用:protoc --go_out=./ *.proto生成的.go文件
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.20.0
// source: userinfo.proto
package userService
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
//enum為關(guān)鍵字,作用為定義一種枚舉類型
type PhoneType int32
const (
PhoneType_MOBILE PhoneType = 0
PhoneType_HOME PhoneType = 1
PhoneType_WORK PhoneType = 2
)
// Enum value maps for PhoneType.
var (
PhoneType_name = map[int32]string{
0: "MOBILE",
1: "HOME",
2: "WORK",
}
PhoneType_value = map[string]int32{
"MOBILE": 0,
"HOME": 1,
"WORK": 2,
}
)
func (x PhoneType) Enum() *PhoneType {
p := new(PhoneType)
*p = x
return p
}
func (x PhoneType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (PhoneType) Descriptor() protoreflect.EnumDescriptor {
return file_userinfo_proto_enumTypes[0].Descriptor()
}
func (PhoneType) Type() protoreflect.EnumType {
return &file_userinfo_proto_enumTypes[0]
}
func (x PhoneType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use PhoneType.Descriptor instead.
func (PhoneType) EnumDescriptor() ([]byte, []int) {
return file_userinfo_proto_rawDescGZIP(), []int{0}
}
//注意:寫完一行以后要注意 ;
type Userinfo struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
Age int32 `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"`
Type PhoneType `protobuf:"varint,3,opt,name=type,proto3,enum=PhoneType" json:"type,omitempty"`
Hobby []string `protobuf:"bytes,4,rep,name=hobby,proto3" json:"hobby,omitempty"`
}
func (x *Userinfo) Reset() {
*x = Userinfo{}
if protoimpl.UnsafeEnabled {
mi := &file_userinfo_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Userinfo) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Userinfo) ProtoMessage() {}
func (x *Userinfo) ProtoReflect() protoreflect.Message {
mi := &file_userinfo_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Userinfo.ProtoReflect.Descriptor instead.
func (*Userinfo) Descriptor() ([]byte, []int) {
return file_userinfo_proto_rawDescGZIP(), []int{0}
}
func (x *Userinfo) GetUsername() string {
if x != nil {
return x.Username
}
return ""
}
func (x *Userinfo) GetAge() int32 {
if x != nil {
return x.Age
}
return 0
}
func (x *Userinfo) GetType() PhoneType {
if x != nil {
return x.Type
}
return PhoneType_MOBILE
}
func (x *Userinfo) GetHobby() []string {
if x != nil {
return x.Hobby
}
return nil
}
var File_userinfo_proto protoreflect.FileDescriptor
var file_userinfo_proto_rawDesc = []byte{
0x0a, 0x0e, 0x75, 0x73, 0x65, 0x72, 0x69, 0x6e, 0x66, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x22, 0x6e, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x69, 0x6e, 0x66, 0x6f, 0x12, 0x1a, 0x0a, 0x08,
0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08,
0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67, 0x65, 0x18,
0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x12, 0x1e, 0x0a, 0x04, 0x74, 0x79,
0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0a, 0x2e, 0x50, 0x68, 0x6f, 0x6e, 0x65,
0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x68, 0x6f,
0x62, 0x62, 0x79, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x05, 0x68, 0x6f, 0x62, 0x62, 0x79,
0x2a, 0x2b, 0x0a, 0x09, 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0a, 0x0a,
0x06, 0x4d, 0x4f, 0x42, 0x49, 0x4c, 0x45, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x4f, 0x4d,
0x45, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x57, 0x4f, 0x52, 0x4b, 0x10, 0x02, 0x42, 0x0f, 0x5a,
0x0d, 0x2e, 0x2f, 0x75, 0x73, 0x65, 0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62, 0x06,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_userinfo_proto_rawDescOnce sync.Once
file_userinfo_proto_rawDescData = file_userinfo_proto_rawDesc
)
func file_userinfo_proto_rawDescGZIP() []byte {
file_userinfo_proto_rawDescOnce.Do(func() {
file_userinfo_proto_rawDescData = protoimpl.X.CompressGZIP(file_userinfo_proto_rawDescData)
})
return file_userinfo_proto_rawDescData
}
var file_userinfo_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_userinfo_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_userinfo_proto_goTypes = []interface{}{
(PhoneType)(0), // 0: PhoneType
(*Userinfo)(nil), // 1: userinfo
}
var file_userinfo_proto_depIdxs = []int32{
0, // 0: userinfo.type:type_name -> PhoneType
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_userinfo_proto_init() }
func file_userinfo_proto_init() {
if File_userinfo_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_userinfo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Userinfo); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_userinfo_proto_rawDesc,
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_userinfo_proto_goTypes,
DependencyIndexes: file_userinfo_proto_depIdxs,
EnumInfos: file_userinfo_proto_enumTypes,
MessageInfos: file_userinfo_proto_msgTypes,
}.Build()
File_userinfo_proto = out.File
file_userinfo_proto_rawDesc = nil
file_userinfo_proto_goTypes = nil
file_userinfo_proto_depIdxs = nil
}
main.go
序列化和 反序列化實(shí)現(xiàn)
package main
import (
"fmt"
"proto_deom/proto/userService"
"google.golang.org/protobuf/proto"
)
func main() {
u := &userService.Userinfo{
Username: "張三",
Age: 20,
Hobby: []string{"吃飯", "睡覺", "寫代碼"},
}
// fmt.Println(u)
fmt.Println(u.GetType())
fmt.Println(u.GetUsername())
fmt.Println(u.GetHobby())
//Protobuf的序列化
data, _ := proto.Marshal(u)
fmt.Println(data)
//Protobuf的反序列化
user := userService.Userinfo{}
proto.Unmarshal(data, &user)
fmt.Printf("%#v\n", user)
fmt.Println(user.GetHobby())
}
(2).案例2
order.proto
訂單相關(guān):
相關(guān)數(shù)據(jù)類型的使用, message嵌套使用
syntax = "proto3";
option go_package = "./orderService";
message Order{
int64 id =1;
double price =2;
string name =3;
string tel=4;
string address=5;
string addTime=6;
//message可以嵌套
// message OrderItem{
// int64 goodsId =1;
// string title=2;
// double price =3;
// int32 num =4;
// }
OrderItem Orderitem =7;
}
message OrderItem{
int64 goodsId =1;
string title=2;
double price =3;
int32 num =4;
}
// protoc --go_out=./ *.proto
orderService/order.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.20.0
// source: order.proto
package orderService
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Order struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Price float64 `protobuf:"fixed64,2,opt,name=price,proto3" json:"price,omitempty"`
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"`
Tel string `protobuf:"bytes,4,opt,name=tel,proto3" json:"tel,omitempty"`
Address string `protobuf:"bytes,5,opt,name=address,proto3" json:"address,omitempty"`
AddTime string `protobuf:"bytes,6,opt,name=addTime,proto3" json:"addTime,omitempty"`
//message可以嵌套
// message OrderItem{
// int64 goodsId =1;
// string title=2;
// double price =3;
// int32 num =4;
// }
Orderitem *OrderItem `protobuf:"bytes,7,opt,name=Orderitem,proto3" json:"Orderitem,omitempty"`
}
func (x *Order) Reset() {
*x = Order{}
if protoimpl.UnsafeEnabled {
mi := &file_order_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Order) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Order) ProtoMessage() {}
func (x *Order) ProtoReflect() protoreflect.Message {
mi := &file_order_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Order.ProtoReflect.Descriptor instead.
func (*Order) Descriptor() ([]byte, []int) {
return file_order_proto_rawDescGZIP(), []int{0}
}
func (x *Order) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
func (x *Order) GetPrice() float64 {
if x != nil {
return x.Price
}
return 0
}
func (x *Order) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *Order) GetTel() string {
if x != nil {
return x.Tel
}
return ""
}
func (x *Order) GetAddress() string {
if x != nil {
return x.Address
}
return ""
}
func (x *Order) GetAddTime() string {
if x != nil {
return x.AddTime
}
return ""
}
func (x *Order) GetOrderitem() *OrderItem {
if x != nil {
return x.Orderitem
}
return nil
}
type OrderItem struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
GoodsId int64 `protobuf:"varint,1,opt,name=goodsId,proto3" json:"goodsId,omitempty"`
Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"`
Price float64 `protobuf:"fixed64,3,opt,name=price,proto3" json:"price,omitempty"`
Num int32 `protobuf:"varint,4,opt,name=num,proto3" json:"num,omitempty"`
}
func (x *OrderItem) Reset() {
*x = OrderItem{}
if protoimpl.UnsafeEnabled {
mi := &file_order_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *OrderItem) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*OrderItem) ProtoMessage() {}
func (x *OrderItem) ProtoReflect() protoreflect.Message {
mi := &file_order_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use OrderItem.ProtoReflect.Descriptor instead.
func (*OrderItem) Descriptor() ([]byte, []int) {
return file_order_proto_rawDescGZIP(), []int{1}
}
func (x *OrderItem) GetGoodsId() int64 {
if x != nil {
return x.GoodsId
}
return 0
}
func (x *OrderItem) GetTitle() string {
if x != nil {
return x.Title
}
return ""
}
func (x *OrderItem) GetPrice() float64 {
if x != nil {
return x.Price
}
return 0
}
func (x *OrderItem) GetNum() int32 {
if x != nil {
return x.Num
}
return 0
}
var File_order_proto protoreflect.FileDescriptor
var file_order_proto_rawDesc = []byte{
0x0a, 0x0b, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb1, 0x01,
0x0a, 0x05, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20,
0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65,
0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x12, 0x12, 0x0a,
0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d,
0x65, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x65, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03,
0x74, 0x65, 0x6c, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x05,
0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x18, 0x0a,
0x07, 0x61, 0x64, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07,
0x61, 0x64, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72,
0x69, 0x74, 0x65, 0x6d, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x4f, 0x72, 0x64,
0x65, 0x72, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x69, 0x74, 0x65,
0x6d, 0x22, 0x63, 0x0a, 0x09, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x18,
0x0a, 0x07, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52,
0x07, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c,
0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x14,
0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x70,
0x72, 0x69, 0x63, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6e, 0x75, 0x6d, 0x18, 0x04, 0x20, 0x01, 0x28,
0x05, 0x52, 0x03, 0x6e, 0x75, 0x6d, 0x42, 0x10, 0x5a, 0x0e, 0x2e, 0x2f, 0x6f, 0x72, 0x64, 0x65,
0x72, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_order_proto_rawDescOnce sync.Once
file_order_proto_rawDescData = file_order_proto_rawDesc
)
func file_order_proto_rawDescGZIP() []byte {
file_order_proto_rawDescOnce.Do(func() {
file_order_proto_rawDescData = protoimpl.X.CompressGZIP(file_order_proto_rawDescData)
})
return file_order_proto_rawDescData
}
var file_order_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_order_proto_goTypes = []interface{}{
(*Order)(nil), // 0: Order
(*OrderItem)(nil), // 1: OrderItem
}
var file_order_proto_depIdxs = []int32{
1, // 0: Order.Orderitem:type_name -> OrderItem
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_order_proto_init() }
func file_order_proto_init() {
if File_order_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_order_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Order); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_order_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*OrderItem); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_order_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_order_proto_goTypes,
DependencyIndexes: file_order_proto_depIdxs,
MessageInfos: file_order_proto_msgTypes,
}.Build()
File_order_proto = out.File
file_order_proto_rawDesc = nil
file_order_proto_goTypes = nil
file_order_proto_depIdxs = nil
}
(3).案例3
goods.proto
RPC服務(wù)的定義
syntax = "proto3";
option go_package = "./goodsService";
//RPC接口, 定義RPC服務(wù),生成的是接口
service GoodsService{
rpc AddGoods(AddGoodsReq) returns (AddGoodsRes);
rpc GetGoods(GetGoodsReq) returns (GetGoodsRes);
}
message GoodsMode{
string title =1;
double price =2;
string content =3;
}
//AddGoods相關(guān)參數(shù)
message AddGoodsReq{
GoodsMode params=1;
}
message AddGoodsRes{
string message =1;
bool success =2;
}
//GetGoods相關(guān)參數(shù)
message GetGoodsReq{
int32 id =1;
}
message GetGoodsRes{
repeated GoodsMode goodsList=1;
}
/*
protoc --go_out=./ *.proto
有RPC接口使用下面方法生成proto go文件
protoc --go_out=plugins=grpc:. *.proto
*/
goodsService/goods.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.20.0
// source: goods.proto
package goodsService
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type AddGoodsReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"`
Price float64 `protobuf:"fixed64,2,opt,name=price,proto3" json:"price,omitempty"`
Content string `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"`
}
func (x *AddGoodsReq) Reset() {
*x = AddGoodsReq{}
if protoimpl.UnsafeEnabled {
mi := &file_goods_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddGoodsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddGoodsReq) ProtoMessage() {}
func (x *AddGoodsReq) ProtoReflect() protoreflect.Message {
mi := &file_goods_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddGoodsReq.ProtoReflect.Descriptor instead.
func (*AddGoodsReq) Descriptor() ([]byte, []int) {
return file_goods_proto_rawDescGZIP(), []int{0}
}
func (x *AddGoodsReq) GetTitle() string {
if x != nil {
return x.Title
}
return ""
}
func (x *AddGoodsReq) GetPrice() float64 {
if x != nil {
return x.Price
}
return 0
}
func (x *AddGoodsReq) GetContent() string {
if x != nil {
return x.Content
}
return ""
}
type AddGoodsRes struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
Success bool `protobuf:"varint,2,opt,name=success,proto3" json:"success,omitempty"`
}
func (x *AddGoodsRes) Reset() {
*x = AddGoodsRes{}
if protoimpl.UnsafeEnabled {
mi := &file_goods_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddGoodsRes) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddGoodsRes) ProtoMessage() {}
func (x *AddGoodsRes) ProtoReflect() protoreflect.Message {
mi := &file_goods_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddGoodsRes.ProtoReflect.Descriptor instead.
func (*AddGoodsRes) Descriptor() ([]byte, []int) {
return file_goods_proto_rawDescGZIP(), []int{1}
}
func (x *AddGoodsRes) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
func (x *AddGoodsRes) GetSuccess() bool {
if x != nil {
return x.Success
}
return false
}
var File_goods_proto protoreflect.FileDescriptor
var file_goods_proto_rawDesc = []byte{
0x0a, 0x0b, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x53, 0x0a,
0x0b, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05,
0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74,
0x6c, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28,
0x01, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74,
0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65,
0x6e, 0x74, 0x22, 0x41, 0x0a, 0x0b, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65,
0x73, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01,
0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x73,
0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75,
0x63, 0x63, 0x65, 0x73, 0x73, 0x32, 0x36, 0x0a, 0x0c, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x53, 0x65,
0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x26, 0x0a, 0x08, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64,
0x73, 0x12, 0x0c, 0x2e, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65, 0x71, 0x1a,
0x0c, 0x2e, 0x41, 0x64, 0x64, 0x47, 0x6f, 0x6f, 0x64, 0x73, 0x52, 0x65, 0x73, 0x42, 0x10, 0x5a,
0x0e, 0x2e, 0x2f, 0x67, 0x6f, 0x6f, 0x64, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62,
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_goods_proto_rawDescOnce sync.Once
file_goods_proto_rawDescData = file_goods_proto_rawDesc
)
func file_goods_proto_rawDescGZIP() []byte {
file_goods_proto_rawDescOnce.Do(func() {
file_goods_proto_rawDescData = protoimpl.X.CompressGZIP(file_goods_proto_rawDescData)
})
return file_goods_proto_rawDescData
}
var file_goods_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_goods_proto_goTypes = []interface{}{
(*AddGoodsReq)(nil), // 0: AddGoodsReq
(*AddGoodsRes)(nil), // 1: AddGoodsRes
}
var file_goods_proto_depIdxs = []int32{
0, // 0: GoodsService.AddGoods:input_type -> AddGoodsReq
1, // 1: GoodsService.AddGoods:output_type -> AddGoodsRes
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_goods_proto_init() }
func file_goods_proto_init() {
if File_goods_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_goods_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddGoodsReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_goods_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddGoodsRes); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_goods_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_goods_proto_goTypes,
DependencyIndexes: file_goods_proto_depIdxs,
MessageInfos: file_goods_proto_msgTypes,
}.Build()
File_goods_proto = out.File
file_goods_proto_rawDesc = nil
file_goods_proto_goTypes = nil
file_goods_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// GoodsServiceClient is the client API for GoodsService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GoodsServiceClient interface {
AddGoods(ctx context.Context, in *AddGoodsReq, opts ...grpc.CallOption) (*AddGoodsRes, error)
}
type goodsServiceClient struct {
cc grpc.ClientConnInterface
}
func NewGoodsServiceClient(cc grpc.ClientConnInterface) GoodsServiceClient {
return &goodsServiceClient{cc}
}
func (c *goodsServiceClient) AddGoods(ctx context.Context, in *AddGoodsReq, opts ...grpc.CallOption) (*AddGoodsRes, error) {
out := new(AddGoodsRes)
err := c.cc.Invoke(ctx, "/GoodsService/AddGoods", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// GoodsServiceServer is the server API for GoodsService service.
type GoodsServiceServer interface {
AddGoods(context.Context, *AddGoodsReq) (*AddGoodsRes, error)
}
// UnimplementedGoodsServiceServer can be embedded to have forward compatible implementations.
type UnimplementedGoodsServiceServer struct {
}
func (*UnimplementedGoodsServiceServer) AddGoods(context.Context, *AddGoodsReq) (*AddGoodsRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method AddGoods not implemented")
}
func RegisterGoodsServiceServer(s *grpc.Server, srv GoodsServiceServer) {
s.RegisterService(&_GoodsService_serviceDesc, srv)
}
func _GoodsService_AddGoods_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddGoodsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GoodsServiceServer).AddGoods(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/GoodsService/AddGoods",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GoodsServiceServer).AddGoods(ctx, req.(*AddGoodsReq))
}
return interceptor(ctx, in, info, handler)
}
var _GoodsService_serviceDesc = grpc.ServiceDesc{
ServiceName: "GoodsService",
HandlerType: (*GoodsServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "AddGoods",
Handler: _GoodsService_AddGoods_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "goods.proto",
}
[上一節(jié)][golang 微服務(wù)] 2. RPC架構(gòu)介紹以及通過RPC實(shí)現(xiàn)微服務(wù)文章來源:http://www.zghlxwxcb.cn/news/detail-685802.html
[下一節(jié)][golang 微服務(wù)] 4. gRPC介紹,Protobuf結(jié)合gRPC 創(chuàng)建微服務(wù)文章來源地址http://www.zghlxwxcb.cn/news/detail-685802.html
到了這里,關(guān)于[golang 微服務(wù)] 3. ProtoBuf認(rèn)識(shí),安裝以及golang 中ProtoBuf使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!