How To use Azure Functions to Send And Read Messages From Azure Service Bus Queues

In this Azure article, we will discuss a step-by-step tutorial to send and read messages using Azure Functions from Service Bus Queues.

How to Use Azure Functions to Send And Read Messages From Azure Service Bus Queues

Below is the functionality we are doing one by one

  • Creating an Azure Service Bus Queue in the Azure Portal
  • Building an HTTP trigger Azure Function for sending the messages to the Queue.
  • Creating a Service Bus Queue triggers the Azure function for reading the messages from the Queue

Before starting the actual functionality, let’s discuss the Prerequisites needed here.

Prerequisites

Assuming you are ready with all the Prerequisites needed here, Let’s start with the actual functionality.

Creating an Azure Service Bus Queue in the Azure Portal

Follow the below two links to create the Azure service bus namespace and queue in the Azure Portal.

How to create Azure Service bus namespace

Creating an Azure Service bus queue in Azure Portal (Follow step-7 to step-9).

Now, I have already created the Azure Service bus namespace and the service Bus Queue.

Creating an HTTP trigger Azure Function for sending the messages to the Queue

Follow the below steps

  1. Launch Visual Studio 2019 on your development machine.
  2. Click on Create a new project button.
  3. Search for Azure Functions –> Select the Azure Functions template –> Click on the Next button.
azure function service bus trigger

4. On Configure your new project window, Provide a name for your project and then choose the location where you wish to save the project –> Click on the Create button.

azure function send message to service bus

5. On the Create a new Azure Functions Application window, fill out the below details

  • Project Template: Choose the HTTP trigger option.
  • Authorization level: Choose Anonymous.
  • Make Sure Azure Functions v3 (.NET Core) is selected.

Finally, click on the Create button. Now, our project has been created successfully.

azure function send message to service bus topic

Let’s modify the class and function name to a meaningful name “SendingMessageToQueue”.

Now, as a next step, we need to install the below Nuget Package

“Microsoft.Azure.Webjobs.Extensions.ServiceBus”. To install the NuGet package, Right click on the Solution –> Select the Manage NuGet Packages for Solution option –> Search for Microsoft.Azure.Webjobs.Extensions.ServiceBus, and then on the search result, click on the Install button.

azure function send message to service bus queue

Now, as a next step, you need to get the connection string of the Azure Service Bus Namespace. For that, you need to navigate to the Service Bus Namespace in the Azure Portal –> Click on the Shared access policies from the left navigation –> Click on the RootManageSharedAccessKey –> Click on the copy button next to the Primary Connection String.

azure function service bus queue trigger example c#

Now, you must add the connection string in your local.settings.json file like below.

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "AzureWebJobsServiceBus": "Your Azure Service Bus Connection String that you have copied above"
  }
}

Now Modify your Function1.cs file like below

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.ServiceBus;

namespace Demotsinfo
{
    public static class SendingMessageToQueue
    {
        [FunctionName("SendingMessageToQueue")]
        [return: ServiceBus("YourQueueName", ServiceBusEntityType.Queue)]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

Now, Press F5 to run the application

We got the desired output. See the below screenshot.

azure function service bus

You can also check in the Service Bus Queue –> Overview tab. You can find the Active Message Count as “1”.

Creating a Service Bus Queue triggers the Azure function for reading the messages from the Queue

You can follow the below steps

  • Right-click on the project –> Select Add –> Then choose the New Azure Function option.
service bus trigger azure function c# example
  • Choose Azure Function –> Provide a meaningful full name –> Click on the Add button as shown in the screenshot below.
service bus queue trigger azure function

Select the Service Bus Queue trigger option–> provide the Queue name –> click the OK button. See the screenshot below for your reference.

send message to service bus topic from azure function

Now, the project will be created like below. Make sure to change the Connection name based on yours.

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace Demotsinfo
{
    public class ReadMessageFromQueue
    {
        [FunctionName("ReadMessageFromQueue")]
        public void Run([ServiceBusTrigger("tsinfoqueue", Connection = "AzureWebJobsServiceBus")]string myQueueItem, ILogger log)
        {
            log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
        }
    }
}

You can see the screenshot below

azure functions service bus trigger

Now, press F5 to run the application. This time, see that it successfully read the active message in the Queue, as shown in the screenshot below, and you are done with the demo.

service bus trigger azure function

You may also like following the articles below

Wrapping Up

This article discussed how to use Azure Functions to send and read messages from Azure Service Bus Queues. Thanks for reading this article !!!

Azure Virtual Machine

DOWNLOAD FREE AZURE VIRTUAL MACHINE PDF

Download our free 25+ page Azure Virtual Machine guide and master cloud deployment today!