RabbitMQ之Routing(路由有选择的接收)
Posted alexephor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RabbitMQ之Routing(路由有选择的接收)相关的知识,希望对你有一定的参考价值。
创建绑定方式
1 channel.queue_bind(exchange="交换器的名字", 2 queue="队列的名字")
绑定使用路由参数(主要避免basic_publish参数混淆)
1 channel.queue_bind(exchange="交换器的名字", 2 queue="队列的名字", 3 routing_key="black")
直接交换
在消息发布与订阅中,消息广播给所有在线的消费者,假如说有时候我们只需要接收严重错误的日志报告写到磁盘中,之前使用的fanout交换,并没有带来太大的灵活性
此时就可以使用直接交换:思想绑定密钥与路由密钥完全匹配的队列才能发收消息
多重绑定
用相同的绑定密钥绑定多个队列
但在这里官方是将每种严重性创建一个新的绑定关系
send_log_direct.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=‘direct_logs‘, exchange_type=‘direct‘) 12 # 日志严重级别 13 severity = sys.argv[1] if len(sys.argv) > 1 else ‘info‘ 14 message = ‘ ‘.join(sys.argv[2:]) or ‘Hello World!‘ 15 channel.basic_publish( 16 exchange=‘direct_logs‘, routing_key=severity, body=message) 17 print(" [x] Sent %r:%r" % (severity, message)) 18 connection.close()
receive_log_direct.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=‘direct_logs‘, exchange_type=‘direct‘) 12 13 result = channel.queue_declare(queue=‘‘, exclusive=True) 14 queue_name = result.method.queue 15 16 severities = sys.argv[1:] 17 if not severities: 18 sys.stderr.write("Usage: %s [info] [warning] [error] " % sys.argv[0]) 19 sys.exit(1) 20 21 for severity in severities: 22 channel.queue_bind( 23 exchange=‘direct_logs‘, queue=queue_name, routing_key=severity) 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之Routing(路由有选择的接收)的主要内容,如果未能解决你的问题,请参考以下文章