NestJS Enterprise Backend APIs · บทเรียน

การผสานรวม RabbitMQ

ผสานรวม RabbitMQ เป็นตัวกลางส่งข้อความเพื่อการสื่อสารแบบอะซิงโครนัสระหว่างไมโครเซอร์วิสของ NestJS ที่ทนทาน

บทเรียน 2 จาก 312 ขั้นตอน

การผสานรวม RabbitMQ เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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!

เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
20
บทเรียน
76

คำถามที่พบบ่อย

บทเรียน “การผสานรวม RabbitMQ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การผสานรวม RabbitMQ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวม RabbitMQ”

ผสานรวม RabbitMQ เป็นตัวกลางส่งข้อความเพื่อการสื่อสารแบบอะซิงโครนัสระหว่างไมโครเซอร์วิสของ NestJS ที่ทนทาน คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน

บทเรียน “การผสานรวม RabbitMQ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม

ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ภาพรวมไมโครเซอร์วิสของ NestJS
  2. การผสานรวม RabbitMQ
  3. การสื่อสารระหว่างบริการ
← กลับไปที่ NestJS Enterprise Backend APIs