Amit
Amit

Reputation: 187

How to receive messages from dead letter queue from azure service bus queue

I have a queue and when I send messages to that queue I see most of the messages are going to its dead letter queue. I want to re submit them to the same queue..
It would be very helpful to me if anyone could suggest me any solution.

Upvotes: 4

Views: 5989

Answers (2)

Le Hai Chau
Le Hai Chau

Reputation: 771

Here is the sample code to read message in deadletter

from azure.servicebus import ServiceBusClient
CONNECTION_STR = "connection string"


servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

queueName ="Queue name"
with servicebus_client:
    # get the Queue Receiver object for the queue
    receiver = servicebus_client.get_queue_receiver(queue_name=queueName,sub_queue="deadletter")
    with receiver:
        for msg in receiver:
            print("Received: " + str(msg))
            # complete the message so that the message is removed from the queue
            receiver.complete_message(msg)
            

Upvotes: 0

anilkumar kasaragadda
anilkumar kasaragadda

Reputation: 175

One possible way is to Receive the messages from the dead letter queue and send them to the normal queue.

Python Code

Step-1: Receive the messages from the dead letter queue:

from azure.servicebus import ServiceBusClient
import json
connectionString = "Your Connection String to Service Bus"
serviceBusClient = ServiceBusClient.from_connection_string(connectionString)
queueName = "Your Queue Name created in the Service Bus"
queueClient = serviceBusClient.get_queue(queueName)
with queueClient.get_deadletter_receiver(prefetch=5) as queueReceiver:
messages = queueReceiver.fetch_next(timeout=100)
for message in messages:
    # message.body is a generator object. Use next() to get the body.
    body = next(message.body)
    # Store the body in some list so that we can send them to normal queue.
    message.complete()

Step-2: Send the messages to the normal queue:

from azure.servicebus import ServiceBusClient, Message
connectionString = "Your Service Bus Connection String"
serviceBusClient = ServiceBusClient.from_connection_string(connectionString)
queueName = "Your Queue name"
queueClient = serviceBusClient.get_queue(queueName)

messagesToSend = [<List of Messages that we got from the dead letter queue>]

with queueClient.get_sender() as sender:
    for msg in messagesToSend:
        sender.send(Message(msg))

Hope this helps.

Upvotes: 4

Related Questions