0Pricing
NestJS Enterprise Backend APIs · 课时

RabbitMQ 集成

将 RabbitMQ 集成为消息代理,为 NestJS 微服务之间提供可靠的异步通信。

RabbitMQ 集成 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

Meet RabbitMQ

Welcome to integrating RabbitMQ with NestJS! RabbitMQ is a popular message broker that helps different parts of your application communicate reliably.

Think of it as a post office for your application's messages. Services can drop off messages, and other services can pick them up when they're ready.

Why Use Message Queues?

In a microservices architecture, direct communication can lead to tight coupling. Message queues solve this by enabling asynchronous communication.

  • Decoupling: Services don't need to know about each other directly.
  • Resilience: If a service is down, messages wait in the queue.
  • Scalability: Easily add more consumers to process messages faster.
  • Load Balancing: Distribute tasks among multiple workers.

Key RabbitMQ Concepts

Let's quickly define the essential terms:

  • Producer: An application that sends messages to the queue.
  • Consumer: An application that receives and processes messages from the queue.
  • Queue: A buffer that stores messages. Messages wait here until a consumer picks them up.
  • Message: The data payload sent by a producer and consumed by a consumer.

NestJS & RabbitMQ Transporter

NestJS provides excellent support for microservices using various transporters. RabbitMQ is one such transporter, enabling robust inter-service communication.

You'll configure your NestJS applications as either a client (producer) that sends messages, or a microservice (consumer) that listens for and processes messages.

Running RabbitMQ Locally

Before integrating, you need a running RabbitMQ instance. The easiest way for local development is using Docker:

docker run -d --hostname my-rabbit --name some-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3-management

This command starts a RabbitMQ server on port 5672 (for AMQP) and 15672 (for management UI).

Producer App Entry Point

This main.ts file is the entry point for a NestJS application configured to act as a producer. It starts an HTTP server that can trigger message sending.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  console.log('Producer HTTP Gateway running on port 3000');
}
bootstrap();

Producer Client Configuration

To send messages, the producer NestJS app needs a client proxy. Configure the ClientsModule in your AppModule to define this RabbitMQ client.

The name ('MESSAGE_SERVICE') is a token used for dependency injection.

import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { AppController } from './app.controller';

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'MESSAGE_SERVICE',
        transport: Transport.RMQ,
        options: {
          urls: ['amqp://localhost:5672'],
          queue: 'my_nest_queue',
          queueOptions: { durable: false },
        },
      },
    ]),
  ],
  controllers: [AppController],
})
export class AppModule {}

Sending an Event Message

Now, inject the configured ClientProxy into a controller or service. Use client.emit() to send an event message to the RabbitMQ queue.

emit() is used for event-based communication where no response is expected.

import { Controller, Get, Inject } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';

@Controller('events')
export class AppController {
  constructor(@Inject('MESSAGE_SERVICE') private client: ClientProxy) {}

  @Get('publish')
  async publishEvent() {
    const payload = { id: 101, text: 'Hello from producer!' };
    this.client.emit('message_event', payload);
    return 'Event sent to RabbitMQ!';
  }
}

Consumer Microservice Entry

This main.ts bootstraps a NestJS application as a microservice. It listens for messages from the specified RabbitMQ queue, acting as a consumer.

Notice NestFactory.createMicroservice instead of create.

import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(
    AppModule,
    {
      transport: Transport.RMQ,
      options: {
        urls: ['amqp://localhost:5672'],
        queue: 'my_nest_queue',
        queueOptions: { durable: false },
      },
    },
  );
  await app.listen();
  console.log('Consumer Microservice is listening on RabbitMQ queue!');
}
bootstrap();

Processing Incoming Messages

In your consumer service, use the @MessagePattern() decorator to define methods that will handle specific messages from the queue.

It's crucial to acknowledge (ack()) messages to inform RabbitMQ they've been processed successfully.

import { Injectable } from '@nestjs/common';
import { MessagePattern, RmqContext, Ctx, Payload } from '@nestjs/microservices';

@Injectable()
export class AppService {
  @MessagePattern('message_event')
  handleMessage(@Payload() data: any, @Ctx() context: RmqContext) {
    console.log('Received message:', data);
    const channel = context.getChannelRef();
    const originalMsg = context.getMessage();
    channel.ack(originalMsg);
    return { status: 'success', data: data };
  }
}

RabbitMQ Quick Check

You've learned how to set up producers and consumers. Let's test your understanding!

Recap: RMQ Integration

You've successfully learned the basics of integrating RabbitMQ with NestJS!

  • RabbitMQ enables asynchronous, decoupled communication.
  • NestJS uses transporters like RabbitMQ for microservices.
  • You configured a NestJS app as a producer (client) to send messages using client.emit().
  • You configured another NestJS app as a consumer (microservice) to receive messages using @MessagePattern().
  • Remember to acknowledge messages for reliability.

This is a powerful pattern for building scalable and robust microservices!

常见问题解答

「RabbitMQ 集成」课时是免费的吗?

是的 — 「RabbitMQ 集成」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 3 节课。

「RabbitMQ 集成」这节课中我会学到什么?

将 RabbitMQ 集成为消息代理,为 NestJS 微服务之间提供可靠的异步通信。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 NestJS Enterprise Backend APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「RabbitMQ 集成」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?

能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. NestJS 微服务概览
  2. RabbitMQ 集成
  3. 服务间通信
← 返回 NestJS Enterprise Backend APIs