- 安装
pip install pika
- 生产者
import pika
credentials = pika.PlainCredentials("root", "root")
conn = pika.BlockingConnection(pika.ConnectionParameters(host="localhost", port=5672, virtual_host="/", credentials = credentials))
channel = conn.channel()
channel.queue_declare(queue="my_queue")
channel.basic_publish(exchange='', routing_key='my_key', body='Hello RabbitMQ')
conn.close()
- 消费者
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters(host="localhost", port=15672, virtual_host="/", credentials= pika.PlainCredentials("root" ,"root")))
chanel = conn.channel("my_chanel1")
chanel.queue_declare(queue="my_queue")
def callback(channel, method, properties, body):
print("接收到消息:",body)
chanel.basic_consume(queue="my_queue", on_message_callback=callback, auto_ack=True)
chanel.start_consuming()