在上一章中,所有的接收端获取的所有的消息。这一章,我们将讨论,一些消息,仍然发送给所有接收端。其中,某个接收端,只对其中某些消息感兴趣,它只想接收这一部分消息。如下图:C1,只对error感兴趣,C2对其他三种甚至对所有都感兴趣,我们该怎么搞呢?
发送端:
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
# 创建一个交换机:direct_logs 类型是: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!'
# 向exchage按照设置的 routing_key=severity 发送message
channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
接收端:
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# 跟发送端一致
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)
# 使用routing_key绑定交换机和队列。广播类型,无需使用这个
# direct类型:会对消息进行精确匹配
# 对个队列使用相同路由key是可以的
for severity in severities:
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()
效果图:
注意:
基于这种模式和上一章,在发送端发消息之前,需要先将接收端启动起来。为啥,前面说了,过期消息不感兴趣,是不会接收的。
在做实验的时候,需要注意