好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Pythonrabbitmq的使用(四)

第三篇说明了关于交换机的使用,已经能实现给所有接收端发送消息,但是如果需要自由定制,有的消息发给其中一些接收端,有些消息发送给另外一些接收端,要怎么办呢?这种情况下就要用到路由键了。

和上一篇相比,改动点主要在两个方面:

设定交换机的类型(type)为direct。上一篇是设置为fanout,表示广播的意思,会将消息发送到所有接收端,这里设置为direct表示要根据设定的路由键来发送消息。
发送信息时设置发送的路由键。

#!/usr/bin/env python
#coding=utf8
import pika
connection= pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel= connection.channel()
#定义交换机,设置类型为direct
channel.exchange_declare(exchange='messages',type='direct')
#定义三个路由键
routings= ['info','warning','error']
#将消息依次发送到交换机,并设置路由键
for routingin routings:
message= '%s message.' % routing
channel.basic_publish(exchange='messages',
routing_key=routing,
body=message)
print message
connection.close() 

和第三篇相比,改动点主要在三个方面:

设定交换机的类型(type)为direct。
增加命令行获取参数功能,参数即为路由键。
将队列绑定到交换机上时,设定路由键。

#!/usr/bin/env python
#coding=utf8
import pika, sys
connection= pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel= connection.channel()
#定义交换机,设置类型为direct
channel.exchange_declare(exchange='messages',type='direct')
#从命令行获取路由键参数,如果没有,则设置为info
routings= sys.argv[1:]
if not routings:
routings= ['info']
#生成临时队列,并绑定到交换机上,设置路由键
result= channel.queue_declare(exclusive=True)
queue_name= result.method.queue
for routingin routings:
channel.queue_bind(exchange='messages',
queue=queue_name,
routing_key=routing)
def callback(ch, method, properties, body):
print " [x] 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() 

以上就是Python rabbitmq的使用(四)的内容,更多相关内容请关注PHP中文网(HdhCmsTestgxlcms测试数据)!

查看更多关于Pythonrabbitmq的使用(四)的详细内容...

  阅读:49次