Home > OS >  How to read from an Azure queue in an Azure function, without a Queue Trigger
How to read from an Azure queue in an Azure function, without a Queue Trigger

Time:01-15

If I have an Azure Function that produces data for a queue, it's very simple: I just set it up as a parameter to the function:

[Queue("myQueue")] ICollector<MyType> myQueue

Is there any analogous way to read data back out of the queue? All the information I can find on reading from queues in Azure Functions talks about Queue Triggers, which is not what I'm trying to do; I want a timer-triggered function that will batch-process elements from a queue. How do I get a "queue reader" in my function?

CodePudding user response:

It sounds like you want a dequeuing process instead of a triggering process. Try this example demonstrated in the Microsoft docs.

https://learn.microsoft.com/en-us/azure/storage/queues/storage-tutorial-queues?tabs=dotnet,environment-variable-windows#dequeue-messages

Extracted below

static async Task<string> RetrieveNextMessageAsync(QueueClient theQueue){
if (await theQueue.ExistsAsync())
{
    QueueProperties properties = await theQueue.GetPropertiesAsync();

    if (properties.ApproximateMessagesCount > 0)
    {
        QueueMessage[] retrievedMessage = await theQueue.ReceiveMessagesAsync(1);
        string theMessage = retrievedMessage[0].Body.ToString();
        await theQueue.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
        return theMessage;
    }

    return null;
}

return null;
}

It looks like you can also adjust the max batch size as well.

CodePudding user response:

I read your question as if you need a timer triggered fuction, to take messages (dequeue) of an queue.

So you need to create an timer triggred function like so:

[FunctionName("TimerTriggerCSharp")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
    DequeueMessage("nyConnection");
}

That then calls your function to dequeue a message of the queue like so from the docs

public void DequeueMessage(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())
    {
        // Get the next message
        QueueMessage[] retrievedMessage = queueClient.ReceiveMessages();

        // Process (i.e. print) the message in less than 30 seconds
        Console.WriteLine($"Dequeued message: '{retrievedMessage[0].Body}'");

        // Delete the message
        queueClient.DeleteMessage(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
    }
}
  • Related