1. 参考链接
https://www.rabbitmq.com/tutorials/tutorial-four-python.html
2. 关键字
- Bindings: 绑定,此参数用于绑定队列和对应的交换机;
- routing_key: 指定特定的绑定关系。eg. A点到B点的一条路的名称,如上海到江苏的沪蓉高速;
- exchange: 特定的交换机的名称,如上例中的上海;
- queue: 队列名称,如上例中的江苏苏州;
- exchange_type:
- fanout: 群发机制,类似于发布订阅方式,A点我只管向外发送消息,B点,C点,我只管接收消息,所有消费者都可以接收到消息;
- direct: 指定绑定关系的发送模式;eg, 上海向苏州,无锡和南京运货物,向苏州运送橘子,向南京运送苹果,向无锡运送橘子和苹果,指定绑定关系后,橘子只能送往苏州和无锡,苹果只能送往南京和无锡;
3. 代码
3.1 生产者:
- 绑定关系有:tom, jerry, bruto;(个人喜欢的卡通人物)
- 交换机名称为:direct_log
- 交换机类型为:direct
import pika
import datetime
import time
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
keys = ['tom', 'jerry', 'bruto']
for key in keys:
count = 0
while count < 5:
message = str(datetime.datetime.now())
channel.basic_publish(
exchange='direct_logs', routing_key=key, body=message)
print(" [x] Sent %r:%r" % (key, message))
time.sleep(1)
count += 1
connection.close()
运行结果为:
3.2 消费者:
接收的绑定关系为:tom, jerry, black, 其中black是前面生产者没有定义的
import pika
connection = 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
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
for key in ['tom', 'jerry', 'black']:
channel.queue_bind(
exchange='direct_logs', queue=queue_name, routing_key=key
)
channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True)
channel.start_consuming()
运行结果:
3.3 结论
- 在生产者中未指定的绑定关系 routing_key, 即使在消费者中想要监听,也是没有消息的;
4. 问题
- 当一段程序既是生产者,又是消费者,应该如何处理?
- 当有模糊匹配的情况出现时,如routing_key,我们希望是模糊匹配,应该如何处理?