简体   繁体   中英

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

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?

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=do.net%2Cenvironment-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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM