Skip to content

Instantly share code, notes, and snippets.

@lowk3v
Last active June 20, 2021 15:40
Show Gist options
  • Save lowk3v/e91300b55e3f0f791674ad86a30bdc2b to your computer and use it in GitHub Desktop.
Save lowk3v/e91300b55e3f0f791674ad86a30bdc2b to your computer and use it in GitHub Desktop.
# GRPC WITH JAVA GOLANG
## 2. gRPC với Protocol Buffer
### 2.1 Protobuf code example
```
syntax = "proto3";
message HelloRequest {
string name = 1;
}
message HelloResponse {
string greet = 1;
}
service WelcomeService {
rpc Hello(HelloRequest) returns(HelloRequest)
}
```
### 2.2 Tại sao lại dùng với Protocol Buffer
- Dễ đọc và hiểu
- Tương tác với nhiều ngôn ngữ tự động
- Đóng gói dạng binary, gói tin nhỏ hơn truyền tin nhanh hơn
- Lựa chọn API hiệu quả cho giao tiếp giữ client-server, server-server
Có thể dùng Google Flatbuffers và Microsoft Bond để thay thế cho Protocol Buffer. Nhưng Protocol buffer là sự lựa chọn tốt nhất
### 2.3 Được hỗ trợ bởi 10 ngôn ngữ chính thức
## 3 HTTP/2 được sử dụng với gRPC
### 3.1 Làm cho gRPC trở nên hiệu quả hơn
- Binary Framing
- Hiệu năng hơn, nhẹ để truyền dữ liệu nhanh
- Nén hiệu quả với protocol buffer
- Nén header với HPACK: giảm overhead và cải thiện hiệu năng
- Multiplexing
- Gửi nhiều request/response parallel qua 1 TCP connection
- Giảm độ trễ và cải thiện mạng.
- Server push:
- 1 request, nhiều response
- Giảm vòng lặp
### 3.2 Cách HTTP/2 làm việc
- Mỗi TCP connection có nhiều stream dữ liệu 2 chiều (đường ống kết nối)
- Mỗi stream có unique ID; Có nhiều tin nhắn 2 chiều
- Mỗi tin nhắn (request/response) chia thành nhiều binary frames
- Mỗi frame (là đơn vị được fragment nhỏ nhất) chứa các thể loại data: headers, settings, priority, data, ...
- frames trong mỗi streams khác nhau sẽ bị xen kẽ và được xử lý lại ở đầu cuối.
### 3.3 So sánh HTTP/2 với HTTP/1
_________________________________________________
| | HTTP/2 | HTTP/1 |
| Dữ liệu | Binary | Text |
| Headers | Được nén | Plain text |
| MultiPlexing | Có | Không |
| Req / connection | multiple | 1 |
| Server push | Có | Không |
| Release | 2015 | 1997 |
-------------------------------------------------
## 4 Chương trình Example (Take note)
- Viết ngôn ngữ proto, sau đó sử dụng protoc (cmd) để compile sang ngôn ngữ cần thiết
- Có maven plugin hỗ trợ compile sang Java
- Ví dụ ta có file Hello.proto -> HelloGrpc.java. Khi viết service cần extend class HelloImplBase
### 4.1 Test gRPC client bằng gRPCurl
- https://github.com/fullstorydev/grpcurl/releases
- Send request: >grpcurl --plaintext localhost:9090 list kev.security.grpc.server/sayHello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment