路由键模糊匹配
使用正则表达式进行匹配。其中“#”表示所有、全部的意思;“*”只匹配到一个词。
匹配规则:
路由键: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'
示例代码:
send4.py:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import pika 4 5 hostname = '192.168.1.133' 6 parameters = pika.ConnectionParameters(hostname) 7 connection = pika.BlockingConnection(parameters) 8 9 # 创建通道 10 channel = connection.channel() 11 # 定义交换机,设置类型为topic 12 channel.exchange_declare(exchange='change_top', type='topic') 13 14 # 定义路由键 15 routings = ['happy.work', 'happy.life', 'sad.work', 'sad.life'] 16 17 # 将消息依次发送到交换机,并设定路由键 18 for routing in routings: 19 message = '%s message.' % routing 20 channel.basic_publish(exchange='change_top', routing_key=routing, body=message) 21 print message 22 23 connection.close()
receive4.py:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import pika 4 import sys 5 6 hostname = '192.168.1.133' 7 parameters = pika.ConnectionParameters(hostname) 8 connection = pika.BlockingConnection(parameters) 9 10 # 创建通道 11 channel = connection.channel() 12 # 定义交换机,设置类型为topic 13 channel.exchange_declare(exchange='change_top', type='topic') 14 15 # 从命令行获取路由参数,如果没有,则报错退出 16 routings = sys.argv[1:] 17 if not routings: 18 print >> sys.stderr, "Usage: %s [routing_key]..." % (sys.argv[0],) 19 exit() 20 21 # 生成临时队列,并绑定到交换机上,设置路由键 22 result = channel.queue_declare(exclusive=True) 23 queue_name = result.method.queue 24 for routing in routings: 25 channel.queue_bind(exchange='change_top', queue=queue_name, routing_key=routing) 26 27 28 def callback(ch, method, properties, body): 29 print " [x] Received %r" % (body,) 30 31 32 channel.basic_consume(callback, queue=queue_name, no_ack=True) 33 34 print ' [*] Waiting for messages. To exit press CTRL+C' 35 channel.start_consuming()
打开四个终端,运行一下命令:
发送端:
接收端: