gRPC
🧠 Tổng quan về gRPC
gRPC (gRPC Remote Procedure Call) là một framework RPC (Remote Procedure Call) mã nguồn mở, được phát triển bởi Google, giúp bạn gọi hàm giữa các dịch vụ phân tán một cách hiệu quả, mạnh mẽ, và ngôn ngữ trung lập.
⚙️ Nguyên lý hoạt động của gRPC
1. Protocol Buffers (Protobuf) là nền tảng chính
gRPC không dùng JSON mà dùng Protocol Buffers (protobuf) để serial hóa dữ liệu.
Protobuf giúp dữ liệu nhỏ gọn, tốc độ cao, và hiệu quả hơn nhiều so với JSON/XML.
Ví dụ định nghĩa:
syntax = "proto3";
service ProductService {
rpc GetProduct(GetProductRequest) returns (ProductResponse);
}
message GetProductRequest {
string product_id = 1;
}
message ProductResponse {
string product_id = 1;
string name = 2;
double price = 3;
}
2. Client gọi phương thức như gọi hàm bình thường
Client sẽ gọi
GetProduct(...)
như gọi một hàm local.Dưới nền, gRPC tạo HTTP/2 connection và gửi dữ liệu protobuf qua đó.
3. Truyền tải dựa trên HTTP/2
gRPC sử dụng HTTP/2 thay vì HTTP/1.1 → cho phép:
Multiplexing (nhiều stream trên một TCP connection)
Full-duplex streaming
Header nén (compressed headers)
Giảm độ trễ
4. Server xử lý và phản hồi
Server nhận gói protobuf từ client
Gọi hàm handler tương ứng
Trả về kết quả dưới dạng protobuf
📬 Quá trình truyền dữ liệu gRPC
✅ Client gọi hàm RPC
📦 Client stub (auto-generated) serialize dữ liệu thành protobuf
🚀 Truyền dữ liệu qua HTTP/2
🖥️ Server nhận dữ liệu → deserialize protobuf
🔁 Server gọi hàm implement thực tế và xử lý
📤 Trả lại response (protobuf) qua HTTP/2
🔄 Client nhận và deserialize về struct/object
🚦 4 loại RPC trong gRPC
Unary
Một request – một response
GetProduct(request) → response
Server Streaming
Một request – nhiều response
ListProducts(request) → stream of Product
Client Streaming
Nhiều request – một response
UploadData(stream of chunk) → response
Bidirectional Streaming
Nhiều request – nhiều response (full-duplex)
Chat(stream) ↔ stream
✅ Ưu điểm của gRPC
⚡ Hiệu suất cao (nhờ Protobuf và HTTP/2)
📦 Message nhỏ gọn
🌐 Hỗ trợ đa ngôn ngữ (Go, Java, Python, etc.)
🔁 Streaming mạnh mẽ (sử dụng lâu dài, thích hợp với microservices, realtime)
🔐 Tích hợp dễ với auth (JWT, TLS, etc.)
❗Lưu ý khi dùng trong Golang
Nên kết hợp với middleware như:
grpc-go interceptors để handle logging, tracing, auth
grpc-gateway nếu cần REST ↔ gRPC bridge
Việc quản lý schema proto nên đặt trong module riêng hoặc proto repo để dễ maintain.
Last updated