【发布时间】:2019-06-07 09:44:34
【问题描述】:
我正在寻找 Python 中的基本 Rabbitmq ack 消费者程序。到目前为止,我有基本的 ack producer 程序。但是不知道对不对。
producer.py
import pika, socket
credentials = pika.PlainCredentials('xxxx', '1234')
hostname = socket.gethostname()
parameters =
pika.ConnectionParameters(host=socket.gethostbyname(hostname),
port=5672, virtual_host='/', credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
msg_props = pika.BasicProperties()
msg_props.content_type = "text/plain"
channel.queue_declare(queue='hello')
if channel.basic_publish(exchange='', routing_key='hello', body='Hello
World!', properties=msg_props):
print ("Message Acknowledged")
else:
print ("Message Lost")
print("[x] Sent 'Hello World!'")
connection.close()
consumer.py
import pika, socket
credentials = pika.PlainCredentials('xxxx', '1234')
hostname = socket.gethostname()
parameters =
pika.ConnectionParameters(host=socket.gethostbyname(hostname),
port=5672, virtual_host='/', credentials=credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_ack(method.delivery_tag)
channel.basic_consume(queue='hello', on_message_callback=callback,
auto_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
>python consumer.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'Hello World!'
>python producer.py
Message Lost
[x] Sent 'Hello World!'
输出:
Though the message is received at the consumer.py program, the delivery
note at producer.py says, "Message Lost", but the note should be "Message Acknowledged".
对于rabbitmq,python中正确的消费者和生产者ack程序是什么?
【问题讨论】:
-
您使用的是哪个 python 版本?它在 python 3.6 中完美运行。
-
python 3.6,你能发布你的消费程序吗?