PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 11, 2022

[FIXED] How to ensure that messages get delivered?

 July 11, 2022     message, pika, python, rabbitmq     No comments   

Issue

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()

Solution

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.



Answered By - eandersson
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing