RabbitMQ Hello World

此代码创建一个生产者,它将两个消息发送到一个队列,一个消费者接收来自该队列的所有消息。

producer.py 的代码(使用 pika 0.10.0 Python 客户端):

import pika

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

channel.queue_declare(queue='queueName')

channel.basic_publish(exchange='',
                      routing_key='queueName',
                      body='Hello')
channel.basic_publish(exchange='',
                      routing_key='queueName',
                      body='World!')
print("Message sent")
connection.close()

consumer.py 的代码:

import pika

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

channel.queue_declare(queue='queueName')

def callback(ch, method, properties, body):
    print("Received message: %r" % body)

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

print('Waiting for messages...')
channel.start_consuming()

输出是:

$ python receive.py
Waiting for messages...
Received message: 'Hello'
Received message: 'World!'

其他语言的 RabbitMQ 教程页面中提供了其他示例。