前面提到的消费者,也就是接收消息程序,分为以下几步处理:
1. 创建连接
2. 建立通道
3. 创建队列(为防止队列不存在,队列存在也不会重新创建)
4. 接收消息(接收消息需要一个回调函数)
5. 启动程序,轮询等待消息
整合代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-02-29 16:30:21
# @Author : mx ([email protected])
# @Link : http://www.shujutiyu.com/
# @Version : $Id$
import os
import pika
conn = None
def callback(ch, method, properties, body):
"""
out body
"""
print " [x] Recived ch {0}".format(ch)
print " [x] Recived method {0}".format(method)
print " [x] Recived properties {0}".format(properties)
print " [x] Recived %r" % (body, )
try:
# get connection
conn = pika.BlockingConnection(pika.ConnectionParameters(
'localhost')
)
# get channel
channel = conn.channel()
# declare queue, 重复声明不会报错,但是没有队列的话直接取用会报错
channel.queue_declare('hello')
# get message
channel.basic_consume(callback, queue='hello', no_ack=True)
print ' [*] Waiting for messages. To exit press CTRL+C'
channel.start_consuming()
except Exception, e:
raise e
finally:
if conn:
conn.close()
注:关于回调函数的参数,后面用到的时候再逐个解析。
运行发送消息程序
[tRabbitMQ@iZ250x18mnzZ src]$ python send_helloworld.py
[x] Sent 'Hello World!'
True
运行接收消息程序
[tRabbitMQ@iZ250x18mnzZ src]$ python recv_helloworld.py
[*] Waiting for messages. To exit press CTRL+C
[x] Recived ch <pika.adapters.blocking_connection.BlockingChannel object at 0x7f61ecc6fa90>
[x] Recived method <Basic.Deliver(['consumer_tag=ctag1.6c2c709930904468b40d0e1a758f7aca', 'delivery_tag=1', 'exchange=', 'redelivered=False', 'routing_key=hello'])>
[x] Recived properties <BasicProperties>
[x] Recived 'Hello, World!'
运行程序启动后,一直在等待获取消息,可以通过Ctrl-C来中止。Hello World基本就结束了,基本知道RabbitMQ基本的使用方法,后续将会进一步对RabbitMQ的使用场景进行解析。