GRPC在golang中使用(windows)

下載protoc編譯器

點擊下載protoc編譯器win64.exe

選擇protoc-3.13.0-win64.zip,解壓後,bin目錄添加到環境變量Path中

下載protoc-gen-go插件

go get github.com/golang/protobuf/protoc-gen-go

在GOPATH下出現protoc-gen-go.exe

編寫proto中間文件

syntax="proto3";
package services;

message ProdRequest {
	int32 prod_id=1;
}

message ProdResponse {
	int32 prod_stock=1;

}

生成Prod.pb.go文件

進入proto文件所在目錄

protoc --go_out=../services Prod.proto

proto文件年增加rpc接口定義

syntax="proto3";
package services;

message ProdRequest {
	int32 prod_id=1;
}

message ProdResponse {
	int32 prod_stock=1;
}

service ProdService {
	rpc GetProdStock (ProdRequest) returns (ProdResponse);
}

生成rpc接口Prod.pb.go文件

protoc --go_out=plugins=grpc:../services Prod.proto

grpc-gateway

作用

對外部提供http方式訪問rpc服務

下載依賴

 go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
 
 go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger

修改proto定義

syntax="proto3";
package services;
import "google/api/annotations.proto";

message ProdRequest {
	int32 prod_id=1;
}

message ProdResponse {
	int32 prod_stock=1;
}

service ProdService {
	rpc GetProdStock (ProdRequest) returns (ProdResponse){
		option (google.api.http) ={
			get: "/v1/prod/{prod_id}"
		};
	}
}

protoc生成gateway類

protoc --grpc-gateway_out=logtostderr=true:../services Prod.proto

依賴庫

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