1

I have an application subscribed on Azure Servicebus Topic who is constantly receiving messages from Stream Analytics. But this application isn't every time subscribed on this Topic. How do I receive only the last message from the topic when the application do the subscription?

  • 1
    Messages are always proceeded as FIFO. Do you have multiple subscriptions into your topic ? What do you mean by "But this application isn't every time subscribed on this Topic" ? – Thomas Sep 24 '16 at 09:08
  • It sounds like you have a case that is not exactly mapping to the ASB and some custom code might be required. Just like @Thomas said, could you elaborate on your app a bit more? – Sean Feldman Sep 24 '16 at 15:10
  • @Thomas I have a subscriber application who sometimes is offline, when it goes online just need to receive the most recent message, not the entire queue of FIFO – Natan Valentim Sep 26 '16 at 16:30
  • So what do you want to do with the other messages ? You ll need to clear you queue first (except the last message). – Thomas Sep 26 '16 at 20:34

1 Answers1

0

Based on your question and your comments, this is what I can advice you:

  • When your application starts, connect to the Azure ServiceBus Subscription and get all messages in the queue.
  • Remove all the previous messages (just complete it) and process the last message.
  • Then you can start listening to new incoming messages.

Based on this answer (Clearing azure service bus queue in one go) :

// Get the message receiver
var messagingFactory = MessagingFactory.CreateFromConnectionString("ServiceBusConnectionString");
var messageReceiver = messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatSubscriptionPath("TopicName", "SubscriptionName"));

BrokeredMessage lastMessage = null;
while (messageReceiver.Peek() != null)
{
    if(lastMessage != null)
    {
        // This was not the last message so complete it.
        lastMessage.Complete();
    }

    // Batch the receive operation
    var brokeredMessages = messageReceiver.ReceiveBatch(300).ToList();

    //Get the last message and remove it from the list
    lastMessage = brokeredMessages.Last();
    brokeredMessages.RemoveAt(brokeredMessages.Count -1);

    // Complete all the other messages
    var completeTasks = brokeredMessages.Select(m => Task.Run(() => m.Complete())).ToArray();

    // Wait for the tasks to complete. 
    Task.WaitAll(completeTasks);                
}

if (lastMessage != null)
{
    // Process your message 
}

// Start listening to new incoming message
messageReceiver.OnMessage(message =>
{
    // Process new messages
}, new OnMessageOptions());
Community
  • 1
  • 1
Thomas
  • 24,234
  • 6
  • 81
  • 125