Chuyển đến nội dung chính

Lesson 17: NestJS Microservices

Microservices Architecture with NestJS. TCP, Redis, RabbitMQ, gRPC transports. Hybrid application, Message patterns, Event-based communication.

💻 Programming — Lesson 17 Lesson 17: NestJS Microservices

NestJS: From Basics to Advanced

Part 5: Microservices, Testing & Production

xdev.asia

1. Microservices in NestJS

NestJS supports many transport layers for microservices:

  • TCP: Built-in, simple, used for internal services
  • Redis: Pub/Sub pattern
  • RabbitMQ (AMQP): Powerful message queue
  • 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. Summary

  • MessagePattern: Request-response (send/receive)
  • EventPattern: Fire-and-forget events (emit/listen)
  • TCP: Simple, internal services
  • RabbitMQ: Reliable messaging, dead letter queues
  • gRPC: High-performance, strongly typed
  • Hybrid: HTTP + Microservice in the same app

The next article will explore Testing in NestJS.