Notice
Recent Posts
Recent Comments
Link
SeouliteLab
파이썬 웹 애플리케이션에서 메시지 큐를 활용한 비동기 통신: django-kombu 사용 방법 본문
django-kombu는 Django 웹 애플리케이션에서 메시지 큐(Message Queue)를 사용하여 비동기 통신을 구현하기 위한 라이브러리입니다. 이를 통해 웹 애플리케이션 간의 통신을 비동기적으로 처리할 수 있습니다. 아래에서 django-kombu의 기능과 사용법을 상세히 소개하겠습니다.
기능 1: RabbitMQ 또는 Redis와의 연동 설정
django-kombu를 사용하여 RabbitMQ 또는 Redis와 연동할 수 있습니다. 이를 통해 웹 애플리케이션 간의 메시지 전달을 위한 메시지 브로커를 설정할 수 있습니다.
예제 1: RabbitMQ와의 연동 설정
# settings.py
BROKER_URL = 'amqp://guest:guest@localhost:5672//'
기능 2: 메시지 송수신 및 처리
django-kombu를 사용하여 메시지를 송수신하고 처리할 수 있습니다. 메시지를 보내고 받는 기능을 통해 웹 애플리케이션 간의 비동기 통신을 구현할 수 있습니다.
예제 2: 메시지 송신 및 처리
# tasks.py
from kombu import Connection, Exchange, Queue
exchange = Exchange('myexchange', type='direct')
queue = Queue('myqueue', exchange=exchange, routing_key='mykey')
def send_message(message):
with Connection('amqp://guest:guest@localhost:5672//') as conn:
producer = conn.Producer(serializer='json')
producer.publish(message, exchange=exchange, routing_key='mykey')
def process_message(body, message):
print("Received message:", body)
message.ack()
기능 3: celery와의 통합
django-kombu를 사용하여 celery와 통합할 수 있습니다. celery를 통해 비동기 작업을 실행하고 django-kombu를 통해 메시지 큐를 관리할 수 있습니다.
예제 3: celery와의 통합
# tasks.py
from celery import shared_task
@shared_task
def add(x, y):
return x + y