How to ensure that messages get delivered?
Asked Answered
N

2

9

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()
Nigeria answered 20/6, 2013 at 21:42 Comment(0)
N
13

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.

Nigeria answered 20/6, 2013 at 21:42 Comment(2)
just out of curiousity, is BlockingConnection() needed in order to call channel.confirm_delivery() ?Fasta
@Jeffrey04: It should be supported in all connection types, as it is defined in the base channel object. github.com/pika/pika/blob/…Nigeria
L
0

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

Last answered 19/8, 2021 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.