npv2k1 / learn-go

Learn go
https://npv2k1.github.io/learn-go/
1 stars 0 forks source link

gRPC là gì? #1

Open npv2k1 opened 1 year ago

npv2k1 commented 1 year ago

gRPC là một giao thức truyền tải dữ liệu được sử dụng để giao tiếp giữa các ứng dụng khác nhau trên mạng. Nó là một giao thức đối tượng (object-based) và có thể được sử dụng trên nhiều ngôn ngữ lập trình khác nhau.

gRPC sử dụng các tiêu chuẩn định nghĩa dịch vụ (service definition) để xác định các hàm (function) có thể được gọi từ một ứng dụng khác, cũng như các tham số đầu vào và đầu ra của chúng. Giao thức gRPC sử dụng cơ chế gửi và nhận dữ liệu dạng các tin nhắn (message) để giao tiếp giữa các ứng dụng. Tin nhắn này có thể được mã hóa bằng các định dạng như JSON hoặc XML, hoặc có thể được mã hóa theo cơ chế biên dịch tĩnh (static typing) như Protocol Buffers.

gRPC có ưu điểm là có thể truyền tải dữ liệu một cách hiệu quả và nhanh hơn so với các giao thức khác như HTTP/REST. Nó cũng hỗ trợ các tính năng như tự động biên dịch, cả hai chiều giao tiếp và các khía cạnh bảo mật như mã hóa SSL.

npv2k1 commented 1 year ago

Certainly! Here is an example of a simple gRPC server in Go:

Copy code package main

import ( "context" "log" "net"

"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"

)

const ( port = ":50051" )

// server is used to implement helloworld.GreeterServer. type server struct{}

// SayHello implements helloworld.GreeterServer func (s server) SayHello(ctx context.Context, in pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.Name}, nil }

func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } This server listens on port 50051 and implements a single gRPC method, SayHello, which takes a HelloRequest message and returns a HelloReply message.

Here is an example of a simple gRPC client in Go that calls the SayHello method:

Copy code package main

import ( "context" "log"

pb "google.golang.org/grpc/examples/helloworld/helloworld"
"google.golang.org/grpc"

)

const ( address = "localhost:50051" defaultName = "world" )

func main() { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn)

r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: defaultName})
if err != nil {
    log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)

} This client establishes a connection to the server, creates a new GreeterClient, and then calls the SayHello method using a HelloRequest message with the name "world". The response from the server is printed to the console.

I hope this helps! Let me know if you have any questions.