Cloud

RabbitMQ를 이용한 메세지 발행/구독 모델

arisu1000 2015. 3. 13. 09:00
워크큐에서는 하나의 메세지가 하나의 워커에게만 전달되지만 발행/구독 모델에서는 하나의 메세지가 모든 구독자에게 전달이 되는 구조.


rabbitmq에서는 메세지를 바로 큐로 보내지 않고 exchange에 먼저 보내는데, 이 exchange 타입을 fanout으로 설정 하면 됨.

예제
emit_log.py
#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
type='fanout')

message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print " [x] Sent %r" % (message,)
connection.close()


receive_logs.py

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
type='fanout')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='logs',
queue=queue_name)

print ' [*] Waiting for logs. To exit press CTRL+C'

def callback(ch, method, properties, body):
print " [x] %r" % (body,)

channel.basic_consume(callback,
queue=queue_name,
no_ack=True)

channel.start_consuming()


참고