Create Azure Function and Read Values From Azure Queue

What is Azure Functions

Azure Functions is a serverless solution that allows you to write less code, maintain less infrastructure, and save on costs. Instead of worrying about deploying and maintaining servers, the cloud infrastructure provides all the up-to-date resources needed to keep your applications running.

The following are a common, but by no means exhaustive, set of scenarios for Azure Functions.

If you want to...then...
Build a web APIImplement an endpoint for your web applications using the HTTP trigger
Process file uploadsRun code when a file is uploaded or changed in blob storage
Build a serverless workflowChain a series of functions together using durable functions
Respond to database changesRun custom logic when a document is created or updated in Cosmos DB
Run scheduled tasksExecute code on pre-defined timed intervals
Create reliable message queue systemsProcess message queues using Queue StorageService Bus, or Event Hubs
Analyze IoT data streamsCollect and process data from IoT devices
Process data in real timeUse Functions and SignalR to respond to data in the moment

Create an Azure Functions

  • Add a new project of type Azure Functions.
  • While adding the functions, it also asks to select the trigger, we will select Queue Trigger
  • It will ask you to add the connection string and the queue name.
  • Give a meaningful name for the connection string field like WeatherDataQueue, add the queueName from where the Azure function needs to read and click next, an azure function with a queue trigger will be created 
  • Add the value of the key WeatherDataQueue in local.settings.json (value can we picked from the connection string value of Queue name from Azure website
  • An Azure function with Queue trigger also expects that all the messages that it receives should be base64 encrypted, so we need to encrypt all the messages using Base64 that we are putting in the queue
  • Go to program.cs file of AzureMessageQueue project and add the encryption option like below

builder.Services.AddAzureClients(builder =>
{
    builder.AddClient<QueueClient, QueueClientOptions>((options, _, _) =>
    {
        options.MessageEncoding = QueueMessageEncoding.Base64;
        var connectionString ="Your connection string";
        var queueName = "Your queue name";
        return new QueueClient(connectionString, queueName, options);
    });
});

  •  The Azure function code will look like the one below:

[FunctionName("QueueStorageTrigger")]

        public void Run([QueueTrigger("add-weatherdata", Connection = "WeatherDataQueue")]string myQueueItem, ILogger log)

        {

            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

        }

  • Now, set both project as start up project and run the solution. As soon as you drop a message in the queue, it will be immediately picked by the Azure function
  • Unlike background task, we don't need to explicitly delete the message from the queue. As soon as the message is successfully processed by the Azure function, it will be automatically deleted from the queue.
  • If we want to test the error case, let's simulate some error message in our Azure function code. In this case, the message won't delete from the queue storage because it has not been processed successfully.
[FunctionName("QueueStorageTrigger")]
        public void Run([QueueTrigger("add-weatherdata", Connection = "WeatherDataQueue")]string myQueueItem, ILogger log)
        {
            if(myQueueItem.Contains("error"))
            {
                throw new Exception("Invalid Input");
            }
            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
        }
  • By default, the queue items are processed for the 5 time and after that it is moved to another queue called add-weatherdata-poison, notice that -poison is the new queue name as per the default naming convention and this queue is automatically created, we don't need to manually create it.
  • What it means that, any message that is moved to -poison key won't be picked up by Azure function and application developer needs to intervene and do the needful action
  • The default behavior can be overridden from the host.json file. For example, if we need to set the Deque count to 2 then, we should write below code 
"extensions": {
    "queues": {
      "maxDequeueCount": 2
    }
  },

How to publish Azure Function 

  • Write click the Azure project name from solution -> Select publish - > Select Azure
  • It gives you different options to choose like Windows, Linux, App Container or Registry
  • For this example, lets proceed with the Windows options and click next
  • Select subscription name and resource group
  • Give a name for this Azure function by clicking on + under function apps section
  • Select the subscription, resource group etc., click Create and Finish
  • The publish profile is successfully created
  • Now click on the publish button and the Azure function is created and available under the resource group on Azure interface





Comments

Popular posts from this blog

Publish .Net Core Web API to Linux Host

Entity Relationship Using EF Core Code First Approach

Web API Using EF Core