RabbitMQ之HelloWorld
Posted Alex
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RabbitMQ之HelloWorld相关的知识,希望对你有一定的参考价值。
1. 安装python的pika模块;
https://pypi.python.org/pypi/pika/0.10.0#downloads
上述地址下载源码,加压,执行如下命令安装:
python setup.py build python setup.py install
2. 测试中包含一个生产者,一个消息队列,一个消费者,使用默认交换;
send.py--生产者,负责发送消息
1 #!/usr/bin/env python 2 import pika 3 4 connection = pika.BlockingConnection(pika.ConnectionParameters( 5 host=‘localhost‘)) 6 channel = connection.channel() 7 8 channel.queue_declare(queue=‘hello‘) 9 10 channel.basic_publish(exchange=‘‘, 11 routing_key=‘hello‘, 12 body=‘Hello World!‘) 13 print(" [x] Sent ‘Hello World!‘") 14 connection.close()
reveiver.py--消费者,负责接收消息
1 #!/usr/bin/env python 2 import pika 3 4 connection = pika.BlockingConnection(pika.ConnectionParameters( 5 host=‘localhost‘)) 6 channel = connection.channel() 7 8 channel.queue_declare(queue=‘hello‘) 9 10 def callback(ch, method, properties, body): 11 print(" [x] Received %r" % body) 12 13 channel.basic_consume(callback, 14 queue=‘hello‘, 15 no_ack=True) 16 17 print(‘ [*] Waiting for messages. To exit press CTRL+C‘) 18 channel.start_consuming()
上述例子中,send.py只执行一次,发送一条消息,receiver.py循环接收消息,直到发送命令结束接收;
发送消息:
python send.py
接收消息:
python receive.py [*] Waiting for messages. To exit press CTRL+C [x] Received ‘Hello World!‘ [x] Received ‘Hello World!‘
以上是关于RabbitMQ之HelloWorld的主要内容,如果未能解决你的问题,请参考以下文章