python rabbitMQ有选择的接收消息(exchange type=direct)或者(exchange_type=topic) 

RabbitMQ还支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,exchange根据 关键字 判定应该将数据发送至指定队列。

import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         exchange_type='direct')

severity = sys.argv[1] if len(sys.argv) > 1 else 'info'#发到那个queue
print(severity)
message = ' '.join(sys.argv[2:]) or 'Hello World! TEST'
channel.basic_publish(exchange='direct_logs',
                      routing_key=severity,
                      body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
direct_product
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         exchange_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]
" % sys.argv[0])
    sys.exit(1)

print(severities)

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(on_message_callback=callback,
                      queue=queue_name,
                      auto_ack=True)

channel.start_consuming()
direct_consumer

更细致的过滤

把上面代码exchange_type改成topic。#创建和消费都要改

要接收运行的所有日志(To receive all the logs run:):
python direct_consumer.py "#"
要从设备“kern”接收所有日志(To receive all logs from the facility "kern":):
python direct_consumer.py "kern.*"
或者,如果您只想了解“关键”日志:(Or if you want to hear only about "critical" logs:)
python direct_consumer.py "*.critical"
您可以创建多个绑定:(You can create multiple bindings:)
python direct_consumer.py "kern.*" "*.critical"
并发出带有路由密钥的日志“内核临界“”类型(And to emit a log with a routing key "kern.critical" type:)
python direct_consumer.py "kern.critical" "A critical kernel error"

















原文地址:https://www.cnblogs.com/anhao-world/p/13883419.html