RabbitMq之路由键模糊匹配
前言
路由键模糊匹配
就是可以使用正则表达式,和常用的正则表示式不同,这里的话“#”表示所有、全部的意思;“*”只匹配到一个词。看完示例就能明白了。
实例的功能大概是这样:
比如你有个知心好朋友,不管开心、伤心、工作上的还是生活上的事情都可以和她说;还有一些朋友可以分享开心的事情;还有一些朋友,你可以把不开心的事情和她说。
路由键
routings = [ 'happy.work', 'happy.life' , 'happy.work.teacher', 'sad.work', 'sad.life', 'sad.work.teacher' ]
"#":匹配所有的路由键
"happy.#":匹配 'happy.work', 'happy.life' , 'happy.work.teacher'
"work.#":无匹配
“happy.*”:匹配 'happy.work', 'happy.life'
"*.work":匹配 'happy.work', 'sad.work'
"*.work.#":匹配 'happy.work', 'happy.work.teacher', 'sad.work', 'sad.work.teacher'
代码
发送端
import pika hostname = '127.0.0.1' parameters = pika.ConnectionParameters(hostname) connection = pika.BlockingConnection(parameters) # 创建通道 channel = connection.channel() # 定义交换机,设置类型为topic channel.exchange_declare(exchange='test_queue_topic', exchange_type='topic') # 定义三个路由键 routings = ['happy.work', 'happy.life', 'sad.work', 'sad.life'] # 将消息依次发送到交换机,并设置路由键 for routing in routings: message = '%s message.' % routing channel.basic_publish(exchange='test_queue_topic', routing_key=routing, body=message) print(message) connection.close()
接受端
import sys, pika hostname = '127.0.0.1' parameters = pika.ConnectionParameters(hostname) connection = pika.BlockingConnection(parameters) # 创建通道 channel = connection.channel() # 定义交换机,设置类型为topic channel.exchange_declare(exchange='test_queue_topic', exchange_type='topic') # 从命令行获取路由键参数,如果没有,则设置为info routings = sys.argv[1:] if not routings: routings = ['info'] # 生成临时队列, result = channel.queue_declare(queue='test_queue_topic', exclusive=True) # exclusive=True 当接收端退出的时候 会销毁那个临时创建的队列 queue_name = result.method.queue for routing in routings: # 绑定到交换机上,设置路由键 channel.queue_bind(exchange='test_queue_topic', queue=queue_name, routing_key=routing) def callback(ch, method, properties, body): print(" [x] Received %r" % (body,)) channel.basic_consume( queue='test_queue_topic', # 指定队列名 on_message_callback=callback, # 从队列里获取消息 auto_ack=False # mq服务器挂掉 防止任务丢失 ) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
代码测试
发送端
接受端
work
happy
所有