二、RabbitMQ安装
服务器端:
yum -y install epel-release
yum -y install rabbitmq-server
systemctl start rabbitmq-server.service #启动服务
systemctl enable rabbitmq-server.service #将服务加入开机启动
# cat /etc/hosts
192.168.31.11 node1.example.com node1
客户端:
安装API,使用API操作RabbitMQ
pip install pika
or
easy_install pika
or
源码https://pypi.python.org/pypi/pika
三、一个简单的RabbitMQ示例
# ######################### 发布者 #########################
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.31.11'))
channel = connection.channel()
# 声明一个queue
channel.queue_declare(queue='hello_chen')
#n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
# exchange类似一个交换机,然后由交换机决定将消息放入那个队列中。这里为空表示交换机不工作。
# 将body中的数据放入名为hello_chen的队列中。
channel.basic_publish(exchange='',
routing_key='hello_chen',
body='Hello World!')
print(" [x] Sent 'Hello World!' ")
connection.close()
发布者
# ########################## 订阅者 ##########################
import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.31.11'))
channel = connection.channel()
#You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
#was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.
# 为什么消费者程序中还需要创建一个队列,是因为不知道生产者和消费者谁先启动。否则会报错。
channel.queue_declare(queue='hello_chen')
def callback(ch, method, properties, body):
print('-->', ch, method, properties)
time.sleep(10) # 模拟任务需要10S
print(" [x] Received %r" % body)
ch.basic_ack(delivery_tag=method.delivery_tag) # 队列消息处理完后发送ack,需要和下面的no_ack一起使用
# 将队列hello_chen中body里面的数据取出去,然后当做参数赋值给callback函数中的body。
channel.basic_consume(callback,
queue='hello_chen'
# no_ack=True #此参数虽然可以增加消息的ack,但对效率会有影响
)
print('
Waiting for messages. To exit press CTRL+C ')
channel.start_consuming()
订阅者