2023年11月22日 星期三

【gRPC】使用Go語言快速架設gRPC Server

安裝環境 Win10 64bit

電腦要先裝有GO


1. 建立專案資料夾 (結構如下) (helloworld資料夾)
專案目錄
- helloworld
- helloworld.proto
- server
- main.go


2. 建立proto文件 (專案目錄/helloworld/helloworld.proto)


3. 安裝編譯 Protocol Buffer 所需的套件
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest


4. 將proto文件編譯成binary
在專案目錄執行
$ protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative helloworld/helloworld.proto


5. 撰寫gRPC Server code (專案目錄/server/main.go)

如果要啟用Server Reflection功能,需import
"google.golang.org/grpc/reflection"
並於main加入reflection.Register
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
log.Printf("server listening at %v", lis.Addr())
// Register reflection service on gRPC server.
reflection.Register(s)


6. 啟動Server
go run server/main.go


7. 使用gRPC Client軟體(如gRPCurl、Evans、Postman Workspaces)來測試
grpc://host ip:port

沒有留言:

張貼留言