Domanda

How do you ensure that messages get delivered with Pika? By default it will not provide you with an error if the message was not delivered succesfully.

In this example several messages can be sent before pika acknowledges that the connection was down.

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
for index in xrange(10):
    channel.basic_publish(exchange='', routing_key='hello', 
                          body='Hello World #%s!' % index)
    print('Total Messages Sent: %s' % x)
connection.close()
È stato utile?

Soluzione

When using Pika the channel.confirm_delivery() flag needs to be set before you start publishing messages. This is important so that Pika will confirm that each message has been sent successfully before sending the next message. This will however increase the time it takes to send messages to RabbitMQ, as delivery needs to be confirmed before the program can proceed with the next message.

channel.confirm_delivery()

try:
   for index in xrange(10):
       channel.basic_publish(exchange='', routing_key='hello', 
                              body='Hello World #%s!' % index)
       print('Total Messages Sent: %s' % x)
except pika.exceptions.ConnectionClosed as exc:
    print('Error. Connection closed, and the message was never delivered.')

basic_publish will return a Boolean depending if the message was sent or not. But, it is important to catch potential exceptions in case the connection is closed during transfer and handle it appropriately. As in those cases the exception will interrupt the flow of the program.

Altri suggerimenti

after trying myself and failing to receive other than ack, i decided to implement a direct reply to the sender.

i followed the example given here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top