RabbitMQ(六):队列绑定关系模糊匹配 topic

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 的方式,队列信息是如何分配的?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值