# RabbitMQ 简单使用 - python **依赖:** ``` pip3 install pika==0.12 ``` **生产者(发送):** ```python import pika # producer connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare('hello') channel.basic_publish(exchange='', routing_key='hello',body='Hello World!') print('[x] sent "Hello World!"') connection.close() # 我们可以在命令行模式运行 rabbitmqctl list_queues 来查看队列 ``` **消费者(接收):** ```python import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() # 如果不声明队列标识的话,如果接收程序先启动,将会报错 channel.queue_declare(queue = 'hello') # 定义callback函数,处理在队列中获取的数据 def callback(ch, method, properties, body): print("[x] Received %r" % body.decode()) # ch.basic_ack(delivery_tag=method.delivery_tag) 告诉队列, 处理完成 channel.basic_consume(callback, queue= 'hello', no_ack = True) # no_ack 不用队列系统发送确认, 默认false. 处理完后没有发送确认或系统崩溃自动分发给其他消费者处理 print('[*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() ``` **参考资料:** - [Python操作rabbitmq 实践笔记](https://www.cnblogs.com/wt11/p/5970297.html) - [报错: basic_consume() got multiple values for keyword argument 'queue'](https://blog.csdn.net/xc_zhou/article/details/91483096)