这是我在使用Python通过PIKA库操作RabbitMQ时产生的错误
python版本是3.7 pika库是1.0.1 RabbitMQ版本是rabbitmq_server-3.7.14
下面是具体代码:send.py
import pika
username="guest"
pwd="guest"
user_pwd=pika.PlainCredentials(username,pwd)
#建立实例
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost',credentials=user_pwd,heartbeat=0))#默认端口5672 可以不写
#声明一个管道可以不写
channel = connection.channel()
#声明queue 队列
channel.queue_declare(queue='hello')
# RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
#一条消息永远不能直接发送到队列,它总是需要通过交换。
channel.basic_publish(exchange='',#交换机
routing_key='hello', # queue名字
body='Hello World! MY name is LWQ')# 消息内容
print (" [x] Sent 'Hello World!'")
connection.close() # 队列关闭
import pika
username="guest"
pwd="guest"
user_pwd=pika.PlainCredentials(username,pwd)
print (' [*] Waiting for messages. To exit press CTRL+C')
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost',credentials=user_pwd,heartbeat=0))#默认端口5672 可以不写
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print (" [x] Received %r" % body )
ch.basic_ack(delivery_tag = method.delivery_tag) # 告诉生成者,消息处理完成
channel.basic_qos(prefetch_count=1) # 类似权重,按能力分发,如果有一个消息,就不在给你发
channel.basic_consume('hello',callback,consumer_tag="hello",auto_ack=True,exclusive=True)
channel.start_consuming()