Using Queue Triggers
Learn how to apply a storage queue trigger in Azure Functions.
Functions can be bound to Azure Queue Storage. Azure Queue Storage is a component of the Azure Storage Account. This technology allows us to use a storage account as a message broker, which is a technology that allows separate applications and services to exchange messages. We can place messages on a queue so they can be read by any eligible subscribers.
We can use Azure Functions both to place messages on a queue and read them from a queue. In this lesson, we will cover both of these functionalities. We will do so with the aid of the following interactive playground:
using Microsoft.AspNetCore.Http; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Threading.Tasks; namespace StorageQueueTriggerDemo { public class Functions { [FunctionName("HttpTrigger")] [OpenApiOperation(operationId: "Run", tags: new[] { "message" })] [OpenApiParameter(name: "message", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "Message to put on the queue")] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "HTTP response")] [return: Queue("message-queue-demo")] public async Task<string> HttpTrigger( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req) { string message = req.Query["message"]; var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); message = message ?? data?.name; if (string.IsNullOrWhiteSpace(message)) return null; return message; } [FunctionName("StorageQueueTrigger")] public void Run([QueueTrigger("message-queue-demo", Connection = "AzureWebJobsStorage")] string myQueueItem, ILogger log) { Console.WriteLine($"C# Queue trigger function processed: {myQueueItem}"); } } }
Adding the required dependencies
Before we can use Azure Queue Storage bindings in a function, we will need to add the Microsoft.Azure.WebJobs.Extensions.Storage
NuGet ...