前一篇博客中,交换区将接收到的消息转发给所有与之绑定的对列。本文介绍另一种模式,交换区根据消息的不同,将消息转发给特定的队列。
发送者
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# 注意exchange_type='direct'
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!'
# 发送消息
# 注意发送消息时的routing_key,后面向接收队列分发消息时,会用到routing_key
channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
接收者
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# 声明交换区,类型为direct
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
# 声明队列
result = channel.queue_declare(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:
# queue_bind方法将队列和交换区绑定起来,绑定关系就是routing_key
# 一个队列可以绑定到多个交换区中,一个交换区也可以被多个队列绑定
# 本例中,一个队列多次和同一个交换区绑定,不过每次绑定的routing_key不一样
# 在上篇博客中,交换区不会查看队列绑定的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(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
发送者发送消息时,会指定routing key;接收者将队列和交换区绑定时,会指定binding_key。
当两者完全匹配时,消息会发送到对应的队列中。
来源:oschina
链接:https://my.oschina.net/u/4293665/blog/4062147