1、发布端代码
# new_direct_p.py
import pika
import sys
# 直连交换机(direct)的使用
# 用来指定某些消费者只收到,它该消费的消息
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# 指定使用 直接交换机
channel.exchange_declare(exchange='direct_logs',exchange_type='direct')
# 获取用户输入,如果没有或长度小于1 那么就 发送info 给对应的消费者,这是只有收取info的消费者,才会收到消息
severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
# 获取输入的消息 运行脚本时的格式为:python new_direact.py info This is info messge.
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()
2、消费端代码
# new_direct_c.py
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]\n" % sys.argv[0])
sys.exit(1)
for severity in severities:
# 循环传入的参数,来绑定routing_key
# 例如:获取到的是info 那么就绑定接收info类型的消息,获取到的是error 那么就绑定接收error类型的错误
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.decode()))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
# 开始消费
channel.start_consuming()
3、如何运行
消费端:
python new_direct_c.py info
python new_direct_c.py warning
python new_direct_c.py error warning
注意:在多个终端中运行接收端代码,可以更好的理解
发布端:
python new_direct_p.py info 这是一条info消息
python new_direct_p.py warning 这是一条警告消息
python new_direct_p.py error 这是一条错误消息消息