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