基础概念
RabbitMQ
接收,存储,转发消息
message
数据
producer
发送消息者
Figure 1: producer
queue
类似于邮箱
Figure 2: queue
consumer
等待接受消息者
Figure 3: consumer
AMQP
通用的消息协议
Hello World
Figure 4: send/receive message
发送消息
Figure 5: send/receive message
- 和RabbitMQ服务器建立连接
#!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel()
- 声明要发送消息的队列
channel.queue_declare(queue='hello')
- 发送消息给exchange
channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'")
- 关闭连接
connection.close()
接收消息
Figure 6: send/receive message
- 创建连接,声明队列
#!/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()