RabbitMQ队列
安装 http://www.rabbitmq.com/install-standalone-mac.html
安装python rabbitMQ module
1
2
3
4
5
6
7
|
pip install pika
or
easy_install pika
or
源码
https:
/
/
pypi.python.org
/
pypi
/
pika
|
生产者端
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author:Madling Xu 4 5 import pika 6 import sys 7 8 connection = pika.BlockingConnection(pika.ConnectionParameters( 9 host='localhost')) 10 channel = connection.channel() 11 12 channel.exchange_declare(exchange='logs', 13 exchange_type='fanout') 14 15 message = ' '.join(sys.argv[1:]) or "info: Hello World!" 16 channel.basic_publish(exchange='logs', 17 routing_key='', 18 body=message) 19 print(" [x] Sent %r" % message) 20 connection.close()
消费者端
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author:Madling Xu 4 5 import pika 6 7 connection = pika.BlockingConnection(pika.ConnectionParameters( 8 host='localhost')) 9 channel = connection.channel() 10 11 channel.exchange_declare(exchange='logs', 12 exchange_type='fanout') 13 14 result = channel.queue_declare(exclusive=True) # 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除 15 queue_name = result.method.queue 16 17 channel.queue_bind(exchange='logs', 18 queue=queue_name) 19 20 print(' [*] Waiting for logs. To exit press CTRL+C') 21 22 23 def callback(ch, method, properties, body): 24 print(" [x] %r" % body) 25 26 27 channel.basic_consume(callback, 28 queue=queue_name, 29 no_ack=True) 30 31 channel.start_consuming()
TypeError: exchange_declare() got an unexpected keyword argument 'type'的解决办法
在用网上的python代码执行rabbitmq案例的时候遇到了一个错误,困惑了好久发现解决办法。
- 原因应该为pika版本不同导致的用法不同,解决方法为把type换成exchange_type