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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/199482.html
標籤:java
上一篇:2020-11-01
