以下是Python rabbitMQ如何实现生产消费者模式的完整攻略,包含两个示例说明。
示例1:简单队列模式
步骤1:安装pika库
在使用Python操作RabbitMQ时,您需要安装pika库。您可以使用以下命令进行安装:
pip install pika
步骤2:发送消息
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='my_queue')
message = 'Hello World!'
channel.basic_publish(exchange='', routing_key='my_queue', body=message)
print("Message sent: ", message)
connection.close()
步骤3:接收消息
import pika
def callback(ch, method, properties, body):
print("Received message: ", body)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='my_queue')
channel.basic_consume(queue='my_queue', on_message_callback=callback, auto_ack=True)
print('Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
步骤4:运行程序
运行发送消息的程序后,您将看到以下输出:
Message sent: Hello World!
运行接收消息的程序后,您将看到以下输出:
Waiting for messages. To exit press CTRL+C
Received message: b'Hello World!'
示例2:工作队列模式
步骤1:安装pika库
同示例1。
步骤2:发送消息
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='my_queue', durable=True)
message = 'Hello World!'
channel.basic_publish(exchange='', routing_key='my_queue', body=message, properties=pika.BasicProperties(delivery_mode=2))
print("Message sent: ", message)
connection.close()
步骤3:接收消息
import pika
import time
def callback(ch, method, properties, body):
print("Received message: ", body)
time.sleep(5)
print("Message processed")
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='my_queue', durable=True)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='my_queue', on_message_callback=callback)
print('Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
步骤4:运行程序
运行发送消息的程序后,您将看到以下输出:
Message sent: Hello World!
运行接收消息的程序后,您将看到以下输出:
Waiting for messages. To exit press CTRL+C
Received message: b'Hello World!'
Message processed
以上就是Python rabbitMQ如何实现生产消费者模式的完整攻略,包含两个示例说明。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python rabbitMQ如何实现生产消费者模式 - Python技术站