和上一篇相比,改动点主要在两个方面:
设定交换机的类型(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的使用(四)的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did86239