How can I manually deadletter a message.(The message is not send to the queue)

102 Views Asked by At

I need to deadletter a message when the API respose is not 200. The message is not initially send to the main queue , I need to directly send the message to the deadletter.

Came accross deadLetter() method , but the argument should be of type 'ServiceBusReceiverClient' and manually converting to ServiceBusReceiverClient type is not possible since the constructors are private. Is there any efficient way to directly deadletter a message through a Java application? The queue is used to send other valid messages as well so making some configuration changes that applies to all messages cannot be implemented .

1

There are 1 best solutions below

0
On

As you mentioned, we can send the messages to the queue first and those messages will sent to the deadLetter queue.

Code :

import com.azure.messaging.servicebus.*;
import com.azure.messaging.servicebus.models.*;

import java.util.List;

public class ServiceBus {

    private static final String SERVICE_BUS_CONNECTION_STRING = "<conec_string>";
    private static final String QUEUE_NAME = "<queue_name>";

    public static void main(String[] args) {
        sendMessageToQueue();
        int responseCode = 404;
        if (responseCode != 200) {
            moveMessageToDeadLetterQueue();
        }
    }

    private static void sendMessageToQueue() {
        ServiceBusSenderClient sender = new ServiceBusClientBuilder()
                .connectionString(SERVICE_BUS_CONNECTION_STRING)
                .sender()
                .queueName(QUEUE_NAME)
                .buildClient();

        ServiceBusMessage message = new ServiceBusMessage("Hi Kamali");

        sender.sendMessage(message);
        System.out.println("Sent message to queue");

        sender.close();
    }
    private static void moveMessageToDeadLetterQueue() {
        ServiceBusReceiverClient receiver = new ServiceBusClientBuilder()
                .connectionString(SERVICE_BUS_CONNECTION_STRING)
                .receiver()
                .queueName(QUEUE_NAME)
                .buildClient();
        Iterable<ServiceBusReceivedMessage> receivedMessages = receiver.receiveMessages(1);

        for (ServiceBusReceivedMessage receivedMessage : receivedMessages) {
            receiver.deadLetter(receivedMessage);
            System.out.println("Moved message to dead-letter queue");
        }
        receiver.close();
    }
}

Output :

It ran successfully as below,

enter image description here

The message is sent to the main queue first as below,

enter image description here

And, quickly sent that message to the deadletter queue as below.

enter image description here