Rabbitmq,Python-ack消费者程序示例

时间:2019-06-07 09:44:34

标签: python rabbitmq

我正在寻找python中的基本Rabbitmq ack消费者程序。到目前为止,我已经有了基本的ack制作程序。但是我不知道这是否正确。

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程序?

1 个答案:

答案 0 :(得分:0)

经过数天的研究,为了获得理想的结果,我终于从链接-RabbitMQ Manual ACK on c# client

中找到了这一点。

在@Evk的帮助下, “ ... BasicAcks是关于发布者确认的,而不是关于接收者的确认。因此,您向代理发布消息,代理(代理,RabbitMQ本身)将在处理此消息时对您进行确认或否定(否定确认)(例如-它将把它写入磁盘以获取持久消息,或将其放入队列中。)请注意,此处不涉及接收器-接收器完全在发布者和RabbitMQ之间。

现在,当您在接收者处确认消息时-再次仅在接收者和RabbitMQ之间-您告诉Rabbit消息已被处理并且可以安全地删除。这样做是为了处理接收方在处理过程中崩溃的情况-然后Rabbit将能够将此消息传递到下一个接收方(如果有)。

请注意,此类架构的整体目的是将发布者和接收者分开-它们不应相互依赖。

如果您有一个接收方(可以有很多),并且想要确保它处理了您的消息,请使用RPC模式:发送消息并等待从该接收方返回另一条消息。”