Python RabbitMQ 使用说明
·
发送消息(生产者)
import pika
# 连接 RabbitMQ
connection = pika.BlockingConnection(pika.ConnectionParameters('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()
接收消息(消费者)
import pika
# 建立连接
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明队列(防止启动时队列不存在)
channel.queue_declare(queue='hello')
# 定义回调函数处理接收到的消息
def callback(ch, method, properties, body):
print(f" [x] Received {body}")
# 告诉 RabbitMQ 该回调会从 'hello' 队列接收消息
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
更多推荐


所有评论(0)