话题模式(Topic)基本思想和路由模式是一样的,只不过路由键支持模糊匹配,符号“#”匹配一个或多个词,符号“*”匹配不多不少一个词
话题模式相当于消息的模糊匹配,或者按照正则匹配。其中
# 是通配符,匹配一个或者多个单词
* 代表匹配一个单词
- send.py
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
exchange_type='topic')
routing_key = ['#', "kern.critical", "A critical kernel error"]
for i in range(10):
message = '{} msg at : routing key {}'.format(i, routing_key[i % 3])
channel.basic_publish(exchange='topic_logs',
routing_key=routing_key[i % 3],
body=message)
print(" [x] Sent :%r" % (message))
connection.close()
- receiver.py
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
exchange_type='topic')
result = channel.queue_declare(queue='',exclusive=True)
queue_name = result.method.queue
binding_key = "#"
channel.queue_bind(exchange='topic_logs',
queue=queue_name,
routing_key=binding_key)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
网友评论