본문 바로가기
Category/Note

비동기 메시지 기반 시스템 구축

by Corinee 2025. 4. 25.
728x90
반응형

RabbitMQ & Kafka 비교 요약

      항목            RabbitMQ                    Kafka
구조 메시지 브로커 (큐 기반) 분산 로그 기반 메시지 스트리밍
용도 작업 큐, 비동기 요청 처리 실시간 로그/이벤트 스트리밍
메시지 처리 방식 Push (consumer에게 전달) Pull (consumer가 직접 가져감)
메시지 순서 보장 보장 파티션 기준 순서 보장
지향하는 목적 워크 큐, 백오피스 이벤트 처리 실시간 데이터 파이프라인, 로그 수집

RabbitMQ 구현 (NestJS 기반)

사용 예: 이메일 발송, 슬랙 알림 등 "백그라운드 처리"

1. RabbitMQ 설치 필요 (Docker)

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

2. NestJS 설정

🔸 producer.module.ts

import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'MAIL_QUEUE',
        transport: Transport.RMQ,
        options: {
          urls: ['amqp://localhost:5672'],
          queue: 'mail_queue',
          queueOptions: { durable: false },
        },
      },
    ]),
  ],
  exports: [ClientsModule],
})
export class ProducerModule {}

🔸 메일 요청 보내기

@Injectable()
export class MailService {
  constructor(@Inject('MAIL_QUEUE') private client: ClientProxy) {}

  async sendWelcomeMail(email: string) {
    await this.client.emit('mail.send', { email });
  }
}

3. Consumer 쪽 (listener)

🔸 main.ts

const app = await NestFactory.createMicroservice(AppModule, {
  transport: Transport.RMQ,
  options: {
    urls: ['amqp://localhost:5672'],
    queue: 'mail_queue',
  },
});
await app.listen();

🔸 메일 consumer

@EventPattern('mail.send')
async handleMail(data: { email: string }) {
  console.log(`📧 이메일 발송 대상: ${data.email}`);
  // 실제 메일 발송 로직 호출
}

Kafka 구현 예시 (NestJS 기반)

사용 예: 주문 시스템, 실시간 로그 수집, 이벤트 중심 구조

1. Kafka 설치 (Docker Compose)

# docker-compose.yml
services:
  zookeeper:
    image: wurstmeister/zookeeper
    ports: ["2181:2181"]

  kafka:
    image: wurstmeister/kafka
    ports: ["9092:9092"]
    environment:
      KAFKA_ADVERTISED_HOST_NAME: localhost
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181

2. NestJS 설정

🔸 producer.module.ts

ClientsModule.register([
  {
    name: 'KAFKA_SERVICE',
    transport: Transport.KAFKA,
    options: {
      client: {
        brokers: ['localhost:9092'],
      },
      consumer: {
        groupId: 'my-kafka-consumer',
      },
    },
  },
]),

🔸 producer.service.ts

@Injectable()
export class OrderService {
  constructor(@Inject('KAFKA_SERVICE') private client: ClientKafka) {}

  async placeOrder(order: OrderDto) {
    this.client.emit('order.placed', order);
  }
}

🔸 consumer.service.ts

@Consumer('order.placed')
async handleOrder(@Payload() data: OrderDto) {
  console.log('🛒 주문 처리:', data);
}

 

RabbitMQ → 작업 큐(이메일, 알림 등)
Kafka → 실시간 데이터 흐름(주문, 로그, 유저 활동 등)

'Category > Note' 카테고리의 다른 글

IntelliJ에서 MCP Server 사용하기  (0) 2025.05.27
더미 이미지  (0) 2025.05.18
터미널에서 mermaid 파일 변환하기  (0) 2025.04.23
express-generator  (0) 2025.04.18
성능 측정 지표 Core Web Vitals (LCP, INP, CLS) 알아보기  (0) 2025.03.23