mandatory message

18 views
Skip to first unread message

Mani Amoozadeh

unread,
Nov 17, 2024, 1:07:44 AM11/17/24
to Pika
I am using the simple python code to test mandatory messages. However, for some reasons the 'on_message_returned' does not work. What is wrong here?

import pika
import time

# Setup connection to RabbitMQ server
connection_param = pika.ConnectionParameters('localhost')
connection = pika.BlockingConnection(connection_param)
channel = connection.channel()

# Declare an exchange (direct type in this case)
exchange_name = 'example_exchange'
channel.exchange_declare(exchange=exchange_name, exchange_type='direct')

# Define a callback for returned messages
def on_message_returned(channel, method, properties, body):
print(f"Message returned: {body}")

channel.add_on_return_callback(on_message_returned)

for idx in range(100):

message = f"Mandatory Message {idx}"

channel.basic_publish(
exchange=exchange_name,
routing_key='non_existent_queue', # Routing key that matches no queue
body=message,
mandatory=True
)

print(f"Sent message: {message}")

time.sleep(5)

# Close the connection
connection.close()

Luke Bakken

unread,
Nov 18, 2024, 10:47:58 AM11/18/24
to Pika
Hello,

Your code has a couple issues. The best way for me to assist you is for you to do the following:

* Create a git repository (on GitHub, GitLab, etc) and add your code.
* Let me know the repository's information, and I can fork it.
* I will open a pull request with changes.

Thanks,
Luke

Mani Amoozadeh

unread,
Nov 18, 2024, 11:52:30 AM11/18/24
to Pika

Luke Bakken

unread,
Nov 18, 2024, 2:04:54 PM11/18/24
to Pika
https://github.com/lukebakken/pika-python-9BC2mYZdOq8

I have added  an updated version of your code, as well as output.txt from running it on my system. As you can see, on_message_returned is called as expected.

My guess is that the issue is with your use of time.sleep. Do NOT do that, because it blocks Pika's I/O loop. You must not block Pika, ever!

Mani Amoozadeh

unread,
Nov 18, 2024, 2:12:59 PM11/18/24
to Pika
Thanks!

Once I added "connection.process_data_events(1)", the code worked as expected.
Why do we have to explicitly call it?

Follow up question:
How did you get the 'output.txt' file?

Luke Bakken

unread,
Nov 18, 2024, 2:19:00 PM11/18/24
to Pika
Reply all
Reply to author
Forward
0 new messages