RabbitMQ之tutorial-4
Tutorial four
ttps://www.rabbitmq.com/tutorials/tutorial-four-python.html
Compared with fanout
mindless broadcast, Receiving messages selectively
Direct exchange
a message goes to the queues whose binding key exactly matches the routing key of the message
Screen Shot 2020-07-22 at 3.49.10 PM
It is perfectly legal to bind multiple queues with the same binding key
Screen Shot 2020-07-22 at 3.49.40 PM
Diect Exchange 和queue做binding的时候
支持一个queue 多个binding key
支持多个queue 同一个binding key
Screen Shot 2020-07-22 at 3.50.21 PM
Sender
import pikaimport sysconnection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost' )) channel = connection.channel() channel.exchange_declare(exchange='direct_logs' , exchange_type='direct' ) severity = sys.argv[1 ] if len (sys.argv) > 2 else 'info' message = ' ' .join(sys.argv[2 :]) or 'Hello World!' channel.basic_publish( exchange='direct_logs' , routing_key=severity, body=message ) print(" [x] Sent %r:%r" % (severity, message)) connection.close()
Receiver
import pikaimport sysconnection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost' )) channel = connection.channel() channel.exchange_declare(exchange='direct_logs' , exchange_type='direct' ) result = channel.queue_declare(queue='' , exclusive=True ) queue_name = result.method.queue severities = sys.argv[1 :] if not severities: sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0 ]) sys.exit(1 ) for sev in severities: channel.queue_bind( exchange='direct_logs' , queue=queue_name, routing_key=sev) print(' [*] Waiting for logs. To exit press CTRL+C' ) def callback (ch, method, properties, body ): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume( queue=queue_name, on_message_callback=callback, auto_ack=True ) channel.start_consuming()
Testing
// receiver 指定binding key python receive_logs_direct.py warning error python receive_logs_direct.py info warning error // sender 指指定routingkey 和 msg python emit_log_direct.py error "Run. Run. Or it will explode." python emit_log_direct.py info "normal event 1" python emit_log_direct.py warning "some warning"