RabbitMQ之tutorial-3

RabbitMQ之tutorial-3

Tutorial Three

https://www.rabbitmq.com/tutorials/tutorial-three-python.html

Screen Shot 2020-12-29 at 12.03.07 PM

The core idea is that producer never sends any msg directly to a queue, quite often the producer even don'y know if a msg will be delivered to any queue at all.

Instead producer send msg to exchange, exchange receive msg from producer and then send to queue.

How exchange decide which queue to send - exchange type

list exchange

rabbitmqctl list_exchanges

Deliver a message to multiple consumers: "publish/subscribe"

fanout - it just broadcasts all the messages it receives to all the queues it knows.

temporary queues

  • We can do this by supplying empty queue parameter to queue_declare: random name
  • exclusive, when connection close delete queue
Screen Shot 2020-07-21 at 10.35.51 PM

emit_log

import pika
import sys

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

channel.exchange_declare(exchange='logs', exchange_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()

exchange type = 'fanout' (will ignore routing key)

recive_log

import pika

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

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


result = channel.queue_declare(queue='', 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, props, body):
print(" [x] %r" % body)


channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True
)

channel.start_consuming()

Bing queue to exchange, so all queue connected to fanout exchange will recive msg

Testing


python receive_log.py > logs_from_rabbit.log
python receive_log.py

python emit_log.py

rabbitmqctl list_bindings