Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 32: Microservices trong NestJS (Phần 1)

Tiếp tục với series, bài này mình sẽ giới thiệu với mọi người về microservices trong NestJS, tách phần gửi mail (Bài 28–30) thành service thông báo riêng.

1. Microservice và transport.

Microservice là ứng dụng chạy ở process riêng, nói chuyện bằng message qua một transport khác HTTP; module, DI, controller, pipe vẫn như cũ. Message có hai kiểu:

  • Request-response: bên gửi send() và chờ kết quả, bên nhận dùng @MessagePattern().
  • Event: bên gửi emit() rồi đi tiếp, bên nhận dùng @EventPattern().

Transport TCP (mặc định) kết nối thẳng tới host:port của service. Transport Redis dùng pub/sub: message không được lưu, lúc gửi không ai nghe là mất.

API phát event qua Redis cho service thông báo đưa vào queue mail (Bài 29), và hỏi số job qua TCP.

npm install @nestjs/microservices

2. Service thông báo là hybrid application.

Các thay đổi khác:

  • Processor, mail-jobs.ts, mail class, templates/ chuyển sang src/notification-service/ (sửa assets trong nest-cli.json).
  • AppModule bỏ BullModule.forRootAsync(), load thay mailConfig bằng notificationsConfig (registerAs('notifications') đọc NOTIFICATIONS_HOST, NOTIFICATIONS_PORT).
  • envSchema chuyển SMTP_URL, MAIL_FROM sang notificationEnvSchema (envSchema.pick() các biến service cần rồi .extend()), thêm NOTIFICATIONS_HOST (mặc định 127.0.0.1), NOTIFICATIONS_PORT (3001).

- src/notification-service/notification-service.module.ts (đoạn trích, bỏ phần import)

// Module gốc của service thông báo (process riêng, không import AppModule)
@Module({
    imports: [
        ConfigModule.forRoot({
            isGlobal: true,
            validationSchema: notificationEnvSchema,
            load: [databaseConfig, mailConfig, notificationsConfig],
        }),
        // Log JSON cùng dạng với API
        LoggerModule.forRoot({ pinoHttp: nativeLoggerOptions }),
        PrismaModule,
        // ... BullModule.forRootAsync(), MailModule.forRootAsync(),
        // BullModule.registerQueue(): chép nguyên từ API sang
    ],
    controllers: [NotificationController],
    providers: [MailProcessor, WelcomeMail, TaskAssignedMail, DueReminderMail],
})
export class NotificationServiceModule {}

NestFactory.createMicroservice() chỉ nghe một transport. Muốn nghe cả Redis và TCP thì tạo app bằng NestFactory.create() rồi gọi connectMicroservice() cho từng transport: hybrid application.

- src/config/redis-options.ts (dùng cho cả service và API)

import type { RedisOptions } from '@nestjs/microservices';

// Transport Redis không nhận URL: tách REDIS_URL thành các option của ioredis
export function redisOptions(redisUrl: string): RedisOptions['options'] {
    const url = new URL(redisUrl);
    return {
        host: url.hostname,
        port: Number(url.port || 6379),
        username: decodeURIComponent(url.username) || undefined,
        password: decodeURIComponent(url.password) || undefined,
        db: Number(url.pathname.slice(1) || 0),
        tls: url.protocol === 'rediss:' ? {} : undefined,
    };
}

- src/notification-service/main.ts (đoạn trích, bỏ phần import)

async function bootstrap() {
    const app = await NestFactory.create(NotificationServiceModule, {
        bufferLogs: true,
    });
    // ... useLogger(), enableShutdownHooks() như main.ts của API
    // Validate payload như HTTP, nhưng lỗi là RpcException.
    // Gọi trước connectMicroservice() để inheritAppConfig áp dụng được
    app.useGlobalPipes(
        new ValidationPipe({
            whitelist: true,
            forbidNonWhitelisted: true,
            exceptionFactory: (errors) =>
                new RpcException(
                    errors
                        .flatMap((error) =>
                            Object.values(error.constraints ?? {}),
                        )
                        .join(', '),
                ),
        }),
    );
    // ... database, tcp: app.get() theo databaseConfig.KEY, notificationsConfig.KEY
    // Hybrid application: một ứng dụng nghe 2 transport
    app.connectMicroservice<MicroserviceOptions>(
        {
            transport: Transport.REDIS, // event từ API (pub/sub)
            options: {
                ...redisOptions(database.redisUrl),
                // Mất kết nối Redis: thử kết nối lại, mỗi lần cách 3 giây
                retryAttempts: 100,
                retryDelay: 3000,
            },
        },
        { inheritAppConfig: true }, // dùng global pipe ở trên
    );
    app.connectMicroservice<MicroserviceOptions>(
        {
            transport: Transport.TCP, // request-response từ API
            options: { host: tcp.host, port: tcp.port },
        },
        { inheritAppConfig: true },
    );
    await app.init(); // không gọi listen(): không mở cổng HTTP
    await app.startAllMicroservices();
}
await bootstrap();

inheritAppConfig: true: microservice dùng global pipe của app (mặc định là không).

3. @EventPattern và @MessagePattern.

- src/notifications/messages.ts (đoạn trích; TaskAssignedEvent, DueRemindersEvent (userIds có @ArrayMaxSize(10_000), day có @Matches(/^\d{4}-\d{2}-\d{2}$/)) viết tương tự; MailStats gồm 5 số waiting... failed)

// Pattern và payload dùng chung: API gửi, service thông báo nhận.
// Payload chỉ chứa id, không chứa email hay token
export const USER_REGISTERED = 'user.registered';
export const TASK_ASSIGNED = 'task.assigned';
export const DUE_REMINDERS = 'reminders.due';
export const MAIL_STATS = 'mail.stats';

export class UserRegisteredEvent {
    @IsInt()
    @IsPositive()
    userId: number;
}

- src/notification-service/notification.controller.ts (đoạn trích; taskAssigned() viết như userRegistered(), dueReminders() gọi addBulk() như Bài 30)

// Nhận message thay cho request HTTP: không có route, chỉ có pattern
@Controller()
export class NotificationController {
    private readonly logger = new Logger(NotificationController.name);

    // constructor: @InjectQueue(MAIL_QUEUE) mailQueue, kèm listener 'error' như Bài 29

    // Event: không trả lời bên gửi. Chỉ nhận qua transport Redis
    @EventPattern(USER_REGISTERED, Transport.REDIS)
    async userRegistered(@Payload() event: UserRegisteredEvent): Promise<void> {
        const job: WelcomeJob = { userId: event.userId };
        await this.mailQueue.add('welcome', job);
    }

    // ...

    // Request-response: giá trị trả về được gửi lại cho bên gọi. Chỉ qua TCP
    @MessagePattern(MAIL_STATS, Transport.TCP)
    async mailStats(): Promise<MailStats> {
        const counts = await this.mailQueue.getJobCounts(
            'waiting',
            'active',
            'delayed',
            'completed',
            'failed',
        );
        return counts as unknown as MailStats; // { waiting: 0, ... }
    }
}

Tham số thứ hai gắn handler vào một transport: gửi mail.stats qua Redis sẽ không ai trả lời. @Payload() lấy dữ liệu message để validate.

4. Gửi message từ API với ClientProxy.

- src/notifications/notifications.module.ts (đoạn trích phần imports; notifications.service.ts export hai token NOTIFICATION_EVENTS = 'NOTIFICATION_EVENTS' và NOTIFICATION_RPC = 'NOTIFICATION_RPC')

        // Mỗi phần tử tạo một ClientProxy, inject bằng name
        ClientsModule.registerAsync([
            {
                name: NOTIFICATION_EVENTS,
                inject: [databaseConfig.KEY],
                useFactory: (database: ConfigType<typeof databaseConfig>) => ({
                    transport: Transport.REDIS,
                    options: redisOptions(database.redisUrl),
                }),
            },
            // NOTIFICATION_RPC: tương tự, inject notificationsConfig.KEY,
            // transport: Transport.TCP, options: { host, port } từ config
        ]),

NotificationsService giữ tên các method nên nơi gọi không đổi:

- src/notifications/notifications.service.ts (đoạn trích; constructor inject hai client bằng @Inject(NOTIFICATION_EVENTS) private readonly events: ClientProxy và @Inject(NOTIFICATION_RPC) ... rpc; sendWelcome(userId) gọi this.emit(USER_REGISTERED, { userId }))

    // send() trả về Observable "lạnh": chỉ gửi khi có subscribe (firstValueFrom)
    mailStats(): Promise<MailStats> {
        return firstValueFrom(this.rpc.send<MailStats>(MAIL_STATS, {}));
    }

    // emit() gửi ngay, không chờ service thông báo xử lý.
    // Không await: Redis lỗi cũng không làm hỏng request đã ghi xong
    private emit(pattern: string, data: object): void {
        this.events.emit(pattern, data).subscribe({
            error: (error: unknown) =>
                this.logger.error(`Không gửi được event ${pattern}`, error),
        });
    }

Route mới GET /api/v1/notifications/mail-stats (@Roles(['admin']), Bài 21) gọi mailStats().

5. Chạy thử.

package.json thêm script start:notifications (nest start --entryFile notification-service/main) và start:notifications:prod (node dist/notification-service/main). Reset dữ liệu như Bài 31, chạy service và API (npm run start:dev) ở hai terminal, đăng ký An, rồi tai ($A) và An ($B) gọi mail-stats:

npm run start:notifications # terminal riêng

curl -X POST http://localhost:3000/api/v1/auth/register -H "Content-Type: application/json" \
    -d '{"name":"An","email":"[email protected]","password":"matkhau123"}'
# Mailpit nhận mail "Chào mừng bạn đến với TaskFlow" gửi tới An

curl http://localhost:3000/api/v1/notifications/mail-stats -H "$A"
# {"data":{"waiting":0,"active":0,"delayed":0,"completed":1,"failed":0}}
curl http://localhost:3000/api/v1/notifications/mail-stats -H "$B" # 403

# Payload sai gửi thẳng vào Redis: service chỉ ghi log lỗi
docker exec taskflow-redis redis-cli PUBLISH user.registered '{"pattern":"user.registered","data":{"userId":"abc"}}'
# "userId must be a positive number, userId must be an integer number"

Tắt service rồi đăng ký Bình: API vẫn trả 201 nhưng mail mất hẳn, bật lại cũng không có (Redis tắt thì emit() lỗi, event cũng mất). mail-stats trả 500 (connect ECONNREFUSED 127.0.0.1:3001).

Như vậy pub/sub còn kém queue ở Bài 29. Việc bắt buộc phải xong như gửi mail cần transport bền: dùng luôn queue BullMQ làm kênh (API thêm job, service chỉ chạy worker), hoặc RabbitMQ, NATS JetStream. Ngoài ra chạy hai instance service thì cả hai nhận cùng event, gửi hai mail. Bài 33 chuyển sang NATS: queue group sửa chuyện gửi trùng, thêm timeout và xử lý lỗi, nhưng NATS core vẫn không lưu message.

Chú ý: TCP và Redis transport không có xác thực, ai kết nối được là gửi được message (như lệnh trên). Chỉ mở trong mạng nội bộ, Redis có mật khẩu, luôn validate payload.

6. Lời kết.

Như vậy mình đã giới thiệu xong phần 1 về microservices trong NestJS: transport TCP và Redis, @MessagePattern, @EventPattern, ClientProxy và hybrid application. Bài sau mình sẽ giới thiệu transport NATS, xử lý lỗi, timeout và khi nào nên tách service.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha