1. 参考链接:
https://www.rabbitmq.com/tutorials/tutorial-five-python.html
2. 代码
生产者:
与使用路由的方式不同,交换机形式为 topic 时,可以做到交换机与绑定信息的模糊匹配,其他参数几乎与 routing 方式一致。
import pika
import datetime, time
if __name__ == "__main__":
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='rabbit_topic', exchange_type='topic')
routings = ['tom.jerry.', '.tom.', '.jerry.', 'tom.jerry.bruto']
for rout in routings:
count = 0
while count < 5:
message = rout + '-->' + str(datetime.datetime.now())
channel.basic_publish(exchange='rabbit_topic',
routing_key=rout,
body=message)
time.sleep(1)
count += 1
print(" [x] Sent %r:%r" % (rout, message))
消费者:
消费者的模糊匹配原则与 * 与 # 有关
- * 表示指定位置精准匹配,如 tom.jerry.bruto 需要匹配时,可以是 *.jerry.* 也可以是 tom.*.*
- # 表示指定位置模糊匹配,如 tom.jerry.bruto 需要匹配时,可以是 tom.# 其中 # 表示后续的匹配规则可以是0个或者多个
import pika
import datetime
if __name__ == "__main__":
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='rabbit_topic', exchange_type='topic')
# routings = ['tom.jerry.', '.tom.', '.jerry.', 'tom.jerry.bruto']
# routings = ['.tom.', 'tom.jerry.bruto']
routings = ['#.tom.', '.jerry.bruto']
# get the temp result of the exchage
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
for rout in routings:
# bind the queue to exchange
channel.queue_bind(exchange='rabbit_topic', queue=queue_name, routing_key=rout)
def call_back(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(queue=queue_name, on_message_callback=call_back, auto_ack=True)
channel.start_consuming()
3. 问题
- 如果出现这样的情况,同一个队列对应两个消费者,同时又使用了 topic 或者 outing 的方式,队列信息是如何分配的?