在前面的章节我们创建了一个简单日志系统,可以广播日志消息到多个接收方
在本 教程中我们添加一个功能 -- 我们将要实现一种可能性即让它只接收已订阅的消息。我们将仅严重错误的日志信息保存到日志文件(以节约磁盘空间),同时仍然能够将所有日志信息打印到控制台上。
前面的例子我们已经创建了bindding,我们可以回忆一下代码:
channel.queue_bind(exchange=exchange_name,
queue=queue_name)
绑定可以设置一个额外的 routing_key 参数。 为了避免和 basic_publish 参数混淆, 我们将这个称谓 绑定key。以下是我们如何使用key创建一个绑定:
channel.queue_bind(exchange=exchange_name,
queue=queue_name,
routing_key='black')
channel.exchange_declare(exchange='direct_logs', type='direct')
然后我们准备发送消息:
channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)
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)
#!/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()
#!/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:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" % 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
例如想要发送日志消息:
$ python emit_log_direct.py error "Run. Run. Or it will explode."
[x] Sent 'error':'Run. Run. Or it will explode.'