SeouliteLab

파이썬 메시지 큐 처리하기: Kombu 모듈 활용법 본문

카테고리 없음

파이썬 메시지 큐 처리하기: Kombu 모듈 활용법

Seoulite Lab 2024. 4. 17. 08:49

Kombu는 파이썬에서 메시지 브로커와 상호 작용하기 위한 라이브러리입니다. RabbitMQ, Redis, Amazon SQS 등 다양한 메시지 브로커와 통합되어 있어, 메시지 큐를 효율적으로 처리할 수 있습니다. 이제 몇 가지 예제를 통해 Kombu 모듈의 활용법을 알아보겠습니다.

예제 1: RabbitMQ로 메시지 전송하기

from kombu import Connection, Exchange, Queue

# RabbitMQ 연결 설정
conn = Connection('amqp://guest:guest@localhost:5672//')

# 메시지 전송을 위한 큐 생성
exchange = Exchange('example-exchange', type='direct')
queue = Queue('example-queue', exchange)

# 연결된 큐에 메시지 전송
with conn.Producer() as producer:
    producer.publish('Hello, RabbitMQ!', exchange=exchange, routing_key='example-queue')

이 예제에서는 Kombu를 사용하여 RabbitMQ로 메시지를 전송하는 방법을 보여줍니다. Connection을 설정하고, Producer를 사용하여 메시지를 특정 큐로 전송합니다.

예제 2: RabbitMQ에서 메시지 수신하기

from kombu import Connection, Exchange, Queue

# RabbitMQ 연결 설정
conn = Connection('amqp://guest:guest@localhost:5672//')

# 큐 설정
exchange = Exchange('example-exchange', type='direct')
queue = Queue('example-queue', exchange)

# 큐에서 메시지 수신
with conn.Consumer(queue) as consumer:
    for message in consumer:
        print("받은 메시지:", message.body)
        message.ack()  # 메시지 확인(acknowledge)

이 예제에서는 Kombu를 사용하여 RabbitMQ에서 메시지를 수신하는 방법을 보여줍니다. Consumer를 사용하여 특정 큐에서 메시지를 수신하고, 받은 메시지를 출력합니다.

예제 3: 메시지 큐에 태스크 전송하기

from kombu import Connection, Exchange, Queue

# RabbitMQ 연결 설정
conn = Connection('amqp://guest:guest@localhost:5672//')

# 큐 설정
exchange = Exchange('example-exchange', type='direct')
queue = Queue('example-queue', exchange)

# 태스크 전송
def process_task(body, message):
    print("처리할 태스크:", body)
    message.ack()

with conn.Consumer(queue) as consumer:
    for message in consumer:
        process_task(message.body, message)

이 예제에서는 Kombu를 사용하여 메시지 큐에 태스크를 전송하고 처리하는 방법을 보여줍니다. 태스크를 처리하는 함수를 정의하고, Consumer를 사용하여 큐에서 메시지를 수신하여 처리합니다.