rabbitmq

介绍

rabbitmq 是消息处理的中间人,可以类比现实生活中的邮局。

术语

  • 生产者

    发送消息的程序叫生产者。

  • 消费者

    接收消息的程序称为消费者。

  • 消息队列

    消息队列驻留在 rabbitmq 中,用来存放消息,理论上消息队列大小 无限制,实际上跟机器的内存和硬盘大小有关。

生产者消费者模型

大部分情况下生成者,消费者,消息队列都在不同的机器上。我们先看一个 hello world 的例子。

模型如下图:

../_images/python-one-overall.png

生产者代码:

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='',
                  routing_key='hello',
                  body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

消费者代码:

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

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

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

RPC 模型

call 方法

cctxt = self.client.prepare(topic=topic or self.topic, version='1.22')
cctxt.call(context, 'do_node_deploy', node_id=node_id,
           rebuild=rebuild, configdrive=configdrive)

cast 方法