gRPC là high-performance RPC framework dùng Protocol Buffers (protobuf) thay vì JSON — phù hợp cho internal microservice communication.
Setup:
typescript
// main.ts — gRPC microservice
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.GRPC,
options: {
package: 'users',
protoPath: join(__dirname, 'users.proto'),
url: '0.0.0.0:5000',
},
});
// Controller
@GrpcMethod('UsersService', 'FindOne')
findOne(data: { id: number }): UserMessage {
return this.usersService.findOne(data.id);
}proto file:
protobuf
service UsersService {
rpc FindOne (FindOneRequest) returns (User);
rpc FindAll (Empty) returns (UsersResponse);
}So sánh gRPC vs REST:
- gRPC: binary (nhỏ hơn 3-10x), strongly typed, bidirectional streaming, HTTP/2
- REST: text-based JSON, human-readable, universal browser support, simpler
Dùng gRPC cho: internal microservice-to-microservice communication có throughput cao. Dùng REST cho: public APIs, browser clients.