本文主要是介绍RabbitMQ消息队列(五):Routing 消息路由(转),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
上篇文章中,我们构建了一个简单的日志系统。接下来,我们将丰富它:能够使用不同的severity来监听不同等级的log。比如我们希望只有error的log才保存到磁盘上。1. Bindings绑定
上篇文章中我们是这么做的绑定:
- channel.queue_bind(exchange=exchange_name,
- queue=queue_name)
实际上,绑定可以带 routing_key 这个参数。其实这个参数的名称和 basic_publish 的参数名是相同了。为了避免混淆,我们把它成为binding key。
使用一个key来创建binding :
- channel.queue_bind(exchange=exchange_name,
- queue=queue_name,
- routing_key='black')
2. Direct exchange
Direct exchange的路由算法非常简单:通过binding key的完全匹配,可以通过下图来说明。exchange X和两个queue绑定在一起。Q1的binding key是orange。Q2的binding key是black和green。
当P publish key是orange时,exchange会把它放到Q1。如果是black或者green那么就会到Q2。其余的Message都会被丢弃。
3. Multiple bindings
4. Emitting logs
首先是我们要创建一个direct的exchange:
- channel.exchange_declare(exchange='direct_logs',
- type='direct')
publish:
- channel.basic_publish(exchange='direct_logs',
- routing_key=severity,
- body=message)
5. Subscribing
对于queue,我们需要绑定severity:
- result = channel.queue_declare(exclusive=True)
- queue_name = result.method.queue
- for severity in severities:
- channel.queue_bind(exchange='direct_logs',
- queue=queue_name,
- routing_key=severity)
6. 最终版本
The code for emit_log_direct.py:
- #!/usr/bin/env python
- import pika
- import sys
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.exchange_declare(exchange='direct_logs',
- type='direct')
- severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
- message = ' '.join(sys.argv[2:]) or 'Hello World!'
- channel.basic_publish(exchange='direct_logs',
- routing_key=severity,
- body=message)
- print " [x] Sent %r:%r" % (severity, message)
- connection.close()
The code for receive_logs_direct.py :
- #!/usr/bin/env python
- import pika
- import sys
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.exchange_declare(exchange='direct_logs',
- type='direct')
- result = channel.queue_declare(exclusive=True)
- queue_name = result.method.queue
- severities = sys.argv[1:]
- if not severities:
- print >> sys.stderr, "Usage: %s [info] [warning] [error]" % \
- (sys.argv[0],)
- sys.exit(1)
- for severity in severities:
- channel.queue_bind(exchange='direct_logs',
- queue=queue_name,
- routing_key=severity)
- 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()
- $ python receive_logs_direct.py warning error > logs_from_rabbit.log
- $ python receive_logs_direct.py info warning error
- [*] Waiting for logs. To exit press CTRL+C
尊重原创,转载请注明出处 anzhsoft: http://blog.csdn.net/anzhsoft/article/details/19630147
参考资料:
1. http://www.rabbitmq.com/tutorials/tutorial-four-python.html
这篇关于RabbitMQ消息队列(五):Routing 消息路由(转)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!