码迷,mamicode.com
首页 > 其他好文 > 详细

RabbitMQ之HelloWorld

时间:2016-03-17 16:31:21      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

 

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

标签:

原文地址:http://www.cnblogs.com/wanpengcoder/p/5287692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!