0Pricing
NestJS Enterprise Backend APIs · 강의

RabbitMQ 통합

NestJS 마이크로서비스 간의 견고한 비동기 통신을 위한 메시지 브로커로 RabbitMQ를 통합합니다.

RabbitMQ 통합은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.

“RabbitMQ 통합”에서 뭘 배우나요?

NestJS 마이크로서비스 간의 견고한 비동기 통신을 위한 메시지 브로커로 RabbitMQ를 통합합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.

“RabbitMQ 통합” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. NestJS 마이크로서비스 개요
  2. RabbitMQ 통합
  3. 서비스 간 통신
← NestJS Enterprise Backend APIs(으)로 돌아가기