前面提到的消費者,也就是接收消息程序,分爲以下幾步處理:
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的使用場景進行解析。