RabbitMQ---Routing

官方文档:https://www.rabbitmq.com/tutorials/tutorial-four-python.html

在这里插入图片描述
queue 与 exchange 绑定时会有绑定键 routing_key,这样 direct 类型的 exchange 就只会将消息发送给绑定键为 routing_key 的 queue。

emit_log_direct.py

#!/usr/bin/env python
import pika
import sys

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

# direct 类型的 exchange 只会将消息发送给绑定键为 routing_key 的 queue
channel.exchange_declare(exchange='direct_logs', exchange_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()

receive_logs_direct.py

#!/usr/bin/env python
import pika
import sys

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

# direct 类型的 exchange 只会将消息发送给绑定键为 routing_key 的 queue
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

result = channel.queue_declare(queue='', 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 称为绑定键
	# routing_key 取决于 exchange 的类型
	# fanout 类型的 exchange 会忽略 routing_key
    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(
    queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

运行结果:

$ python3 receive_logs_direct.py info warning error
 [*] Waiting for logs. To exit press CTRL+C
 [x] 'error':b'Run. Run. Or it will explode.'
$ python3 receive_logs_direct.py info 
 [*] Waiting for logs. To exit press CTRL+C
 [x] 'info':b'Run. Run. Or it will explode.'
$ python3 emit_log_direct.py error "Run. Run. Or it will explode."                    
 [x] Sent 'error':'info Run. Run. Or it will explode.'
 
$ python3 emit_log_direct.py info "Run. Run. Or it will explode."                     
 [x] Sent 'info':'Run. Run. Or it will explode.'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值