1. Microservices trong NestJS
NestJS hỗ trợ nhiều transport layers cho microservices:
- TCP: Built-in, đơn giản, dùng cho internal services
- Redis: Pub/Sub pattern
- RabbitMQ (AMQP): Message queue mạnh mẽ
- gRPC: High-performance RPC framework
- Kafka: Event streaming platform
npm install @nestjs/microservices
2. TCP Transport
// Microservice (User Service) — main.ts
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
UserModule,
{
transport: Transport.TCP,
options: { host: '0.0.0.0', port: 3001 },
},
);
await app.listen();
// User Service — Controller
import { MessagePattern, Payload } from '@nestjs/microservices';
@Controller()
export class UserController {
@MessagePattern({ cmd: 'get_user' })
getUser(@Payload() data: { id: string }) {
return this.usersService.findById(data.id);
}
@MessagePattern({ cmd: 'create_user' })
createUser(@Payload() data: CreateUserDto) {
return this.usersService.create(data);
}
}
// API Gateway — gọi microservice
@Module({
imports: [
ClientsModule.register([{
name: 'USER_SERVICE',
transport: Transport.TCP,
options: { host: 'user-service', port: 3001 },
}]),
],
})
export class AppModule {}
// Gateway Controller
@Controller('users')
export class UsersController {
constructor(@Inject('USER_SERVICE') private userClient: ClientProxy) {}
@Get(':id')
getUser(@Param('id') id: string) {
return this.userClient.send({ cmd: 'get_user' }, { id });
}
}
3. RabbitMQ Transport
npm install amqplib amqp-connection-manager
// Order Service — main.ts
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
OrderModule,
{
transport: Transport.RMQ,
options: {
urls: [process.env.RABBITMQ_URL],
queue: 'orders_queue',
queueOptions: { durable: true },
},
},
);
// Event-based: Publish event
@Injectable()
export class OrderService {
constructor(@Inject('NOTIFICATION_SERVICE') private client: ClientProxy) {}
async createOrder(dto: CreateOrderDto) {
const order = await this.orderRepo.save(dto);
// Emit event (fire & forget)
this.client.emit('order_created', {
orderId: order.id,
userId: order.userId,
total: order.total,
});
return order;
}
}
// Notification Service — lắng nghe event
@Controller()
export class NotificationController {
@EventPattern('order_created')
handleOrderCreated(@Payload() data: OrderCreatedEvent) {
this.notificationService.sendOrderConfirmation(data);
}
}
4. gRPC Transport
npm install @grpc/grpc-js @grpc/proto-loader
// proto/user.proto
syntax = "proto3";
package user;
service UserService {
rpc FindOne (UserById) returns (User) {}
rpc FindAll (Empty) returns (Users) {}
}
message UserById {
string id = 1;
}
message User {
string id = 1;
string name = 2;
string email = 3;
}
message Users {
repeated User users = 1;
}
message Empty {}
// gRPC Microservice
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
UserModule,
{
transport: Transport.GRPC,
options: {
package: 'user',
protoPath: join(__dirname, 'proto/user.proto'),
url: '0.0.0.0:5000',
},
},
);
// gRPC Controller
@Controller()
export class UserController {
@GrpcMethod('UserService', 'FindOne')
findOne(data: { id: string }): User {
return this.usersService.findById(data.id);
}
@GrpcMethod('UserService', 'FindAll')
findAll(): { users: User[] } {
return { users: this.usersService.findAll() };
}
}
5. Hybrid Application (HTTP + Microservice)
// main.ts — vừa HTTP vừa microservice
const app = await NestFactory.create(AppModule);
// Kết nối thêm microservice transport
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.RMQ,
options: {
urls: [process.env.RABBITMQ_URL],
queue: 'orders_queue',
},
});
await app.startAllMicroservices();
await app.listen(3000);
6. Tổng kết
- MessagePattern: Request-response (send/receive)
- EventPattern: Fire-and-forget events (emit/listen)
- TCP: Đơn giản, internal services
- RabbitMQ: Reliable messaging, dead letter queues
- gRPC: High-performance, strongly typed
- Hybrid: HTTP + Microservice trong cùng 1 app
Bài tiếp theo sẽ tìm hiểu Testing trong NestJS.