zpjx 发表于 2017-12-9 13:37:15

python中RabbitMQ的使用(路由键)

  1.简介
  当我们希望每个接收端接收各自希望的消息时,我们可以使用路由键,此时交换机的类型为direct。
  2.工作原理
  每个接收端的消息队列在绑定交换机的时候,可以设定相应的路由键。
  发送端通过交换机发送信息时,可以指明路由键 ,交换机会根据路由键把消息发送到相应的消息队列。
  接收端可以根据路由键获取不同的消息队列。
  3.代码
  send3.py



#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pika

hostname = '192.168.1.133'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)

# 创建通道
channel = connection.channel()
# 定义交换机,设置类型为direct
channel.exchange_declare(exchange='change_dir', type='direct')

# 定义三个路由键
routings = ['info', 'warning', 'error']

# 将消息依次发送到交换机,并设置路由键
for routing in routings:
   message = '%s message.' % routing
   channel.basic_publish(exchange='change_dir', routing_key=routing, body=message)
   print message

connection.close()
  receive3.py



#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pika
import sys

hostname = '192.168.1.133'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)

# 创建通道
channel = connection.channel()
# 定义交换机,设置类型为direct
channel.exchange_declare(exchange='change_dir', type='direct')

# 从命令行获取路由键参数,如果没有,则设置为info
16 routings = sys.argv
17 if not routings:
18   routings = ['info']

# 生成临时队列,并绑定到交换机上,设置路由键
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
for routing in routings:
   channel.queue_bind(exchange='change_dir', queue=queue_name, routing_key=routing)

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

channel.basic_consume(callback, queue=queue_name, no_ack=True)

print '
[*] Waiting for messages. To exit press CTRL+C'
channel.start_consuming()
  4.示例演示
  打开三个终端,在前两个运行receive3.py:
  python receive3.py info warning

  python receive3.py error
  
  第三个终端运行send3.py:

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

页: [1]
查看完整版本: python中RabbitMQ的使用(路由键)