python中RabbitMQ的使用(路由键)

1.简介python

当咱们但愿每一个接收端接收各自但愿的消息时,咱们能够使用路由键,此时交换机的类型为direct。post

2.工做原理spa

每一个接收端的消息队列在绑定交换机的时候,能够设定相应的路由键。命令行

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

接收端能够根据路由键获取不一样的消息队列。blog

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.示例演示it

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

python receive2.py info warning

python receive2.py error

 第三个终端运行send2.py:

查看接收端的消息:

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

 

 

相关文章
相关标签/搜索