[gRPC] มาฝึกเขียน gRPC กัน (Hands-On)
จากบทความที่แล้วที่เราพูดถึงแค่ทฤษฎี บทความนี้เรามาลงมือทำกัน (มี source code ให้ดาวน์โหลดด้านล่าง)
ก่อนอื่นเรามา Setup โปรเจคกันก่อน (ในบทความนี้เราจะเขียน Golang กัน)
- ติดตั้ง go ให้เรียบร้อย https://golang.org/doc/install
- ติดตั้ง VS code แล้วลง extension ชื่อว่า vscode-proto3 และ Clang-Format
- ติดตั้ง Clang-Format
$ brew install clang-format
- ติดตั้ง Protoc
brew install protobuf
หลังจากที่เซ็ต GOPATH, GOROOT, GOBIN กันเรียบร้อยแล้ว ขั้นตอนต่อไปคือลง package ที่ชื่อว่า grpc โดยใช้คำสั่ง
$ go get -u google.golang.org/grpc
อ่านเพิ่มเติมเกี่ยวกับ package นี้ได้ที่ https://github.com/grpc/grpc-go
ขั้นต่อต่อไปคือติดตั้ง package ที่มีชื่อว่า protobuf
$ go get -u github.com/golang/protobuf/protoc-gen-go
ข้อมูลเพิ่มเติมเกี่ยวกับ package นี้ https://github.com/golang/protobuf
ทีนี้เราก็พร้อมสำหรับการ generate code โดยใช้ไฟล์ .proto แล้ว
ต่อไปให้สร้างไฟล์ .proto ชื่อว่า greet.proto (ขอเริ่มจาก API แบบ Unary ก่อนละกัน)
Unary
syntax = "proto3";package greet;option go_package="greetpb";message Greeting { string first_name = 1; string last_name = 2;}message GreetRequest { Greeting greeting = 1;}message GreetResponse { string result = 1;}service GreetService { // Unary rpc Greet(GreetRequest) returns (GreetResponse) {};
}
compile โค้ดจากไฟล์ greet.proto
$ protoc greet.proto --go_out=plugins=grpc:.
สร้าง Boilerplate กัน
เขียนโค้ดฝั่ง Server
เขียนโค้ดฝั่ง Client
สั่งรัน server และ client (เปิด terminal ขึ้นมา 2 sessions)
$ go run server.go$ go run client
ผลลัพธ์
Server Streaming
เพิ่มโค้ดต่อไปนี้ในไฟล์ greet.proto
message GreetManyTimesRequest { Greeting greeting = 1;}message GreetManyTimesResponse { string result = 1;}
service GreetService {
... // Server Streaming rpc GreetManyTimes(GreetManyTimesRequest) returns (stream GreetManyTimesResponse) {};
}
สั่ง compile ใหม่
$ protoc greet.proto --go_out=plugins=grpc:.
server.go
client.go
ผลลัพธ์
Client Streaming
เพิ่มโค้ดต่อไปนี้ในไฟล์ greet.proto
message LongGreetRequest { Greeting greeting = 1;}message LongGreetResponse { string result = 1;}
service GreetService {
... // Client Streaming rpc LongGreet(stream LongGreetRequest) returns (LongGreetResponse) {};
}
สั่ง compile ใหม่
$ protoc greet.proto --go_out=plugins=grpc:.
server.go
client.go
ผลลัพธ์
Bi-Directional Streaming
เพิ่มโค้ดต่อไปนี้ในไฟล์ greet.proto
message GreetEveryoneRequest { Greeting greeting = 1;}message GreetEveryoneResponse { string result = 1;}service GreetService { ...
// BiDi Streaming rpc GreetEveryone(stream GreetEveryoneRequest) returns(stream GreetEveryoneResponse) {};
}
สั่ง compile ใหม่
$ protoc greet.proto --go_out=plugins=grpc:.
server.go
client.go
ผลลัพธ์
Download source code: https://github.com/nanthan/grpc-beginner หรือ https://github.com/simplesteph/grpc-go-course
References: