python成长之路【第十二篇】:RabbitMQ入门

一、RabbitMQ介绍

解释RabbitMQ,就不得不提到AMQP(Advanced Message Queuing Protocol)协议。 AMQP协议是一种基于网络的消息传输协议,它能够在应用或组织之间提供可靠的消息传输。RabbitMQ是该AMQP协议的一种实现,利用它,可以将消息安全可靠的从发 送方传输到接收方。简单的说,就是消息发送方利用RabbitMQ将信息安全的传递给接收方。

RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。

MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。

二、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()
订阅者
原文地址:https://www.cnblogs.com/wooya/p/5983520.html