初探RabbitMQ——“Hello World”

Posted by BlkArt on June 10, 2015

前面已经搭建好了实验环境,本节就在这个环境中来个“Hello World”,进而了解下RabbitMQ的工作流程。

大体介绍下本次实验流程:编写一个Python脚本(send.py),向RabbitMQ Server发送一个“Hello World”,编写另外一个脚本(receive.py),用于从RabbitMQ Server接收“Hello World”。

注意: 本次实验用到了pika库

编写send.py『rabbitmq-1』

# vim send.py
import pika

# 定义rabbitmq服务器地址
rabbitmq_server = '192.168.2.81'

# 创建一个新的连接
connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_server))
# 创建一个新的channel
channel = connection.channel()

# 创建一个新的queue
channel.queue_declare(queue='hello')

# 发送一条消息
channel.basic_publish(exchange='',routing_key='hello',body='Hello World!')

print " [x] Sent 'Hello World!'"

# 关闭连接
connection.close()

编写receive.py『rabbitmq-2』

# vim receive.py
import pika  

# 定义rabbitmq服务器地址
rabbitmq_server = '192.168.2.81'

# 创建一个新的连接  
connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_server))  
# 创建一个新的channel
channel = connection.channel()  

# 创建一个新的queue
channel.queue_declare(queue='hello')

# 定义回调函数,处理接收到的消息
def callback(ch, method, properties, body):
    print " [x] Received %r" % (body,)

# 订阅queue
channel.basic_consume(callback,queue='hello',no_ack=True)

print '[*] Waiting for messages. To exit press CTRL+C'
# 循环监听,等待消息
channel.start_consuming()

在『rabbitmq-2』节点运行receive.py脚本,等待接收消息

[rabbitmq-2] # python receive.py
[*] Waiting for messages. To exit press CTRL+C

在『rabbitmq-1』节点运行send.py脚本,发送消息

[rabbitmq-1] # python send.py
[x] Sent 'Hello World!'

此时在『rabbitmq-2』节点即可接收到以下消息

[x] Received 'Hello World!'