Unary RPCs
Unary RPCs là phương thức gọi function từ xa trong đó máy khách gửi một yêu cầu đến máy chủ và nhận lại một phản hồi duy nhất, giống như lệnh gọi hàm thông thường.

Tạo 1 file unary.go tại server , trong file này , chúng ta implement function SayHelloUnary được define trong file proto
package main
import (
"context"
"fmt"
pb "greet/proto"
"log"
)
func (s *Server) SayHelloUnary(ctx context.Context, in *pb.HelloRequest) (*pb.HelloResponse, error) {
log.Printf("Receive Message: %s", in.Msg)
return &pb.HelloResponse{
Msg: fmt.Sprintf("Hello from server"),
}, nil
}Tại client , chúng ta gọi đến server đang chạy ở port 8080 bằng cách tạo 1 file main.go tại folder client với nội dung:
package main
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "greet/proto"
"io"
"log"
"time"
)
const port = "8080"
func main() {
conn, err := grpc.Dial("localhost:"+port, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("Cannot connect with error %v", err)
}
defer conn.Close()
client := pb.NewGreetServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
//Unary
response, err := client.SayHelloUnary(ctx, &pb.HelloRequest{Msg: "Hello From Client"})
if err != nil {
log.Fatalf("Unary calling error %v", err)
}
log.Printf("Receive message: %s", response.Msg)
}Tương tự cách tạo server như bài trước , để tạo 1 client gọi đến gRPC server chúng ta cần xác định 1 yếu tố:
- Địa chỉ của gRPC Server đang chạy
- Function cần gọi
Chạy file main.go trên và quan sát kết quả
Bạn thấy bài này thế nào?