Grpc&&protocol buffer
關于下載下傳:首先下載下傳一個protobuf
- 對于mac系統就
就可以了。然後可以brew install protobuf
看下安裝的版本号,預設按最新版。protoc --version
- 如果想手動按就去官網下載下傳
https://github.com/protocolbuffers/protobuf/releases
下載下傳go語言的proto插件
- protoc -h 看到沒有 --go_out 就沒法生成go的pb.proto代碼,是以需要下載下傳 go的插件-----執行下面指令,從源端下載下傳
-
go get -u -v github.com/golang/protobuf/protoc-gen-go
下載下傳grpc
-
go get -u google.golang.org/grpc
- 如果用go module的話 ,如下引入,可以改成想要的版本
require (
google.golang.org/grpc v1.33.1
google.golang.org/protobuf v1.25.0
)
###根據proto生成 pb.go
先展示一下目錄結構
$ tree
.
├── README.md
├── client.go
├── db
│ └── mongo
│ └── pool.go
├── go.mod
├── go.sum
├── grpc
│ ├── user
│ │ └── user.pb.go
│ └── user.proto
├── server.go
└── service
└── userservice.go
其中user.proto如下所示
syntax = "proto3";
// user 包
package user;
// 指定 go 的包路徑及包名
// option go_package="github.com/isMe/grpcdemo.git/grpc/user;user";
// User 服務及服務接口的定義
service User {
rpc UserIndex(UserIndexRequest) returns (UserIndexResponse) {}
rpc UserId(UserIdRequest) returns (UserIdResponse){}
rpc UserDelete(UserDeleteRequest) returns (UserDeleteResponse) {}
rpc UserInsert(UserInsertRequest) returns (UserInsertResponse){}
}
// 枚舉類型
enum EnumUserSex {
SEX_FEMALE = 0; // 枚舉類型必須以 0 起始
SEX_MALE = 1;
}
// 使用者實體模型
message UserEntity {
string name = 1;
int32 age = 2;
repeated string hobby = 3;
EnumUserSex sex = 4;
}
// User 服務的各個接口的請求/響應結構
message UserIndexRequest {
int32 page = 1;
int32 pageSize = 2;
}
message UserIndexResponse {
int32 err = 1;
string msg = 2;
// 傳回一個 UserEntity 對象的清單資料
repeated UserEntity data = 3;
}
message UserIdRequest {
int64 id = 1;
}
message UserIdResponse {
int32 err = 1;
string msg = 2;
UserEntity data = 3;
}
message UserDeleteRequest {
int64 id = 1;
}
message UserDeleteResponse {
int32 err = 1;
string msg = 2;
}
message UserInsertRequest {
UserEntity data = 1;
}
message UserInsertResponse {
int32 err = 1;
string msg = 2;
}
- 生成pb.go 在grpc目錄下執行
protoc --proto_path=. --go_out=plugins=grpc:./user user.proto
- –proto_path是proto檔案所在位置
- –go_out這個是go的輸出,要加上grpc插件
- 最後跟上要編譯的proto檔案
以上操作已經把API都建立好了,接下來隻需要寫impl實作的server端就行了,如果另一端調用隻需建立該API服務的grpcClient即可。代碼庫如下,把server和client run一下就行了。
我把整個demo的grpc服務放到GitHub上面了,可以點選>>>> 下載下傳源碼
https://github.com/StrandingHeart/GrpcDemo