RabbitMQ之Topics(更加细粒度的接收消息)

组播

  功能更加的强大,通过'#'(哈希)绑定键绑定时候,可以接收所有的消息,此时与路由无关,此时就像fanout交换器中一样

  当在绑定中不使用特殊字符'*','#'接收消息的时候,此时就跟direct一样

RabbitMQ之Topics(更加细粒度的接收消息)_第1张图片

 

 topic_send.py

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import pika
 5 import sys
 6 
 7 credentials = pika.PlainCredentials('admin', 'admin123456')
 8 connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.1.6', credentials=credentials))
 9 channel = connection.channel()
10 
11 channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
12 
13 routing_key = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info'
14 message = ' '.join(sys.argv[2:]) or 'Hello World!'
15 channel.basic_publish(
16     exchange='topic_logs', routing_key=routing_key, body=message)
17 print(" [x] Sent %r:%r" % (routing_key, message))
18 connection.close()

topic_recevie.py

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import pika
 5 import sys
 6 
 7 credentials = pika.PlainCredentials('admin', 'admin123456')
 8 connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.1.6', credentials=credentials))
 9 channel = connection.channel()
10 
11 channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
12 
13 result = channel.queue_declare('', exclusive=True)
14 queue_name = result.method.queue
15 
16 binding_keys = sys.argv[1:]
17 if not binding_keys:
18     sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
19     sys.exit(1)
20 
21 for binding_key in binding_keys:
22     channel.queue_bind(
23         exchange='topic_logs', queue=queue_name, routing_key=binding_key)
24 
25 print(' [*] Waiting for logs. To exit press CTRL+C')
26 
27 
28 def callback(ch, method, properties, body):
29     print(" [x] %r:%r" % (method.routing_key, body))
30 
31 
32 channel.basic_consume(
33     queue=queue_name, on_message_callback=callback, auto_ack=True)
34 
35 channel.start_consuming()

 最终效果就可以达到选择性接收并且还能够更加细粒度的可以接收消息

RabbitMQ之Topics(更加细粒度的接收消息)_第2张图片

你可能感兴趣的:(RabbitMQ之Topics(更加细粒度的接收消息))