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 教程頁面中提供了其他示例。