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

第 17 課:NestJS 微服務

使用 NestJS 的微服務架構。 TCP、Redis、RabbitMQ、gRPC 傳輸。混合應用程式、訊息模式、基於事件的通訊。

💻 程式設計 — 第 17 課 第 17 課:NestJS 微服務

NestJS:從基礎到高級

第 5 部分:微服務、測試與生產

亞洲開發網

1.NestJS中的微服務

NestJS 支持微服务的许多传输层:

  • 傳輸控制協定:內置,簡單,用於內部服務
  • 雷迪斯:Pub/Sub 模式
  • RabbitMQ (AMQP):強大的消息隊列
  • 遠程過程調用:高效能RPC框架
  • 卡夫卡:事件流平台
npm install @nestjs/microservices

2.TCP傳輸

// 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傳輸

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 傳輸

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. 混合應用(HTTP + 微服務)

// 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);

六、總結

  • 訊息模式:請求-回應(發送/接收)
  • 事件模式:即發即忘事件(發出/監聽)
  • 傳輸控制協定:簡單的內部服務
  • RabbitMQ:可靠的消息传递、死信队列
  • 遠程過程調用:高性能、強型
  • 油電混合:同一個應用程式中的 HTTP + 微服務

下一篇文章將探討 在 NestJS 中測試。