python中RabbitMQ的使用(路由键)

1.简介

当我们希望每个接收端接收各自希望的消息时,我们可以使用路由键,此时交换机的类型为direct。

2.工作原理

每个接收端的消息队列在绑定交换机的时候,可以设定相应的路由键。

发送端通过交换机发送信息时,可以指明路由键 ,交换机会根据路由键把消息发送到相应的消息队列。

接收端可以根据路由键获取不同的消息队列。

3.代码

send2.py

import pika

connection=pika.BlockingConnection(pika.ConnectionParameters("localhost"))
# 创建通道
channel=connection.channel()
channel.exchange_declare(exchange="change_dir",exchange_type="direct")
# 定义三个路由键
routings=["info","warning","error"]
# 将消息依次发送到交换机,并设置路由键
for routing in routings:
    messege='%s message'% routing
    channel.basic_publish(exchange="change_dir",routing_key=routing,body=messege)
    print(messege

          )
connection.close()

receive2.py

import pika
import sys
connection=pika.BlockingConnection(pika.ConnectionParameters("localhost"))
# 创建通道
channel=connection.channel()
# 定义交换机,设置类型为direct
channel.exchange_declare(exchange="change_dir",exchange_type="direct")
# 从命令行获取路由键参数,如果没有,则设置为info
routings=sys.argv[1:]
if not routings:
    routings=["info"]
# 生成临时队列,并绑定到交换机上,设置路由键
result = channel.queue_declare('',exclusive=True)
queue_name = result.method.queue

for routing in routings:
    channel.queue_bind(queue_name,"change_dir",routing_key=routing)

def callback(ch,method,properties,body):
    print(" [x] Received %r" % body)

channel.basic_consume(queue_name,callback,auto_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

4.示例演示

打开三个终端,在前两个运行receive3.py:

python receive2.py info warning

python receive2.py error

 第三个终端运行send2.py:

查看接收端的消息:

我们可以发现,接收端只能获取指定路由键的消息队列。

 

原文地址:https://www.cnblogs.com/Hale-wang/p/11821237.html