RabbitMQ - 5 topic模式
前言:direct模式相当于精准匹配,有精准就有模糊,对吧,接下来看看模糊匹配。
Topic exchange
区别:routing_key 必须是一系列的单词,以逗号分隔;这些单词可以是任意的,但通常它们会指定一些与信息相关的特性,最多255字节的限制。 routing_key 中两个特殊的单词: * 可以代替一个单词 # 可以代替0个或多个单词

for example: ---------------------------------------- | routing_key | queue | ---------------------------------------- | quick.orange.rabbit | Q1 Q2 | ---------------------------------------- | lazy.orange.elephant | Q1 Q2 | ---------------------------------------- | quick.orange.fox | Q1 | ---------------------------------------- | lazy.brown.fox | Q2 | ---------------------------------------- | lazy.pink.rabbit | Q2 | ---------------------------------------- | quick.brown.fox | discarded | ---------------------------------------- | orange | discarded | ---------------------------------------- | quick.orange.male.rabbit| discarded | ---------------------------------------- | lazy.orange.male.rabbit | Q2 | ----------------------------------------
Topic 这种交换机制也如其他exchange一样强大。当 routing_key 为 '#' 时分发效果和fanout一样。当 '*' 和 '#' 在routing_key中都没出现时,分发效果同direct一样。
Putting it all together
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 = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(
exchange='topic_logs', routing_key=routing_key, body=message)
print(" [x] Sent %r:%r" % (routing_key, message))
connection.close()
receive.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')
result = channel.queue_declare('', exclusive=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
sys.exit(1)
for binding_key in binding_keys:
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(
queue=queue_name, on_message_callback=callback, auto_ack=True)
channel.start_consuming()

浙公网安备 33010602011771号