官方文档:https://www.rabbitmq.com/tutorials/tutorial-four-python.html
queue 与 exchange 绑定时会有绑定键 routing_key,这样 direct 类型的 exchange 就只会将消息发送给绑定键为 routing_key 的 queue。
emit_log_direct.py
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# direct 类型的 exchange 只会将消息发送给绑定键为 routing_key 的 queue
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
severity = sys.argv[1] if len(sys.argv) > 1 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()
receive_logs_direct.py
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# direct 类型的 exchange 只会将消息发送给绑定键为 routing_key 的 queue
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 severity in severities:
# routing_key 称为绑定键
# routing_key 取决于 exchange 的类型
# fanout 类型的 exchange 会忽略 routing_key
channel.queue_bind(
exchange='direct_logs', queue=queue_name, routing_key=severity)
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()
运行结果:
$ python3 receive_logs_direct.py info warning error
[*] Waiting for logs. To exit press CTRL+C
[x] 'error':b'Run. Run. Or it will explode.'
$ python3 receive_logs_direct.py info
[*] Waiting for logs. To exit press CTRL+C
[x] 'info':b'Run. Run. Or it will explode.'
$ python3 emit_log_direct.py error "Run. Run. Or it will explode."
[x] Sent 'error':'info Run. Run. Or it will explode.'
$ python3 emit_log_direct.py info "Run. Run. Or it will explode."
[x] Sent 'info':'Run. Run. Or it will explode.'