Home > OS >  Azure Service Bus - Leave message
Azure Service Bus - Leave message

Time:11-20

(FYI - I am new ASB)

A couple of questions around Azure Service Bus:

  1. How do you get a message from a Queue but leave it there until its' TTL expires? I would have thought simply not calling CompleteMessageAsync would do just that, but it appears to get removed regardless.

  2. How do get a message from a Queue, but only dequeue (remove) it when received by a specific receiver?

Message.ApplicationProperties["ReceiverId"].ToString() == "123" // now you can remove it

Thanks

CodePudding user response:

How do you get a message from a Queue but leave it there until its' TTL expires?

You can peek at messages rather than receive them. The problem is that the message will be picked up again and again until the delivery count exceeds the maximum and the message will dead-letter, which you don't want to happen. I would review what you're trying to achieve here as it's a contradictory setup. You want the message to have a TTL in anticipation that it's not picked up, but then you want to probe it until TTL expires continuedly.

How do get a message from a Queue, but only dequeue (remove) it when received by a specific receiver?

My advice is don't use a queue for that. If you target a specific destination, express it with your entity topology. For example: publish a message on a topic and have different subscriptions based on the subscriber identification. That way you can have messages for specific subscribers, where a logical subscriber can be scaled out.

CodePudding user response:

1-Use the PeekMessage:

You can peek at the messages in the queue without removing them from the queue by calling the PeekMessages method. If you don't pass a value for the maxMessages parameter, the default is to peek at one message.

//-------------------------------------------------
// Peek at a message in the queue
//-------------------------------------------------
public void PeekMessage(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    if (queueClient.Exists())
    { 
        // Peek at the next message
        PeekedMessage[] peekedMessage = queueClient.PeekMessages();

        // Display the message
        Console.WriteLine($"Peeked message: '{peekedMessage[0].Body}'");
    }
}

https://docs.microsoft.com/en-us/azure/storage/queues/storage-dotnet-how-to-use-queues?tabs=dotnet

2-you can also use PeekMessage, check for the property you want (ReceiverId), and it case it's the right one, just complete the message:

// ServiceBusReceiver 
await receiver.CompleteMessageAsync(receivedMessage);
  • Related