Send and receive messages to an azure service bus Queue from an Azure function.

Rehan KhanDyn365CE2 years ago13 Views

to send messages to an Azure service bus from an Azure function and receive the message from another Azure function. I will create two Azure functions, one to send(sender function) messages and another one to receive(receiver function) messages. For messaging we will use Azure service bus Queue. To learn more about Azure service bus Queue click here.

Prerequisites
Please note below azure components are required to achieve this requirement.

  • Azure trial / Pay as you go plan .
  • Make sure to select the Azure development workload during visual studio installation.
  • Azure service bus Queue .
  • Azure functions .

Create an Azure service bus.
Subscription -Select the subscription you have opted for.
Resource Group -Create a new resource group if you don’t have existing.
Namespace Name -Add your preferred namespace for the Azure service bus.
Location -Select the location based on your preference.
Pricing tier -Select the pricing tier .

Click on Review & Create Azure service Bus .

Create a Queue

Keep all the default settings while creating the queue then click on Create.

Create Azure function project in Visual studio

Azure Functions has Triggers and Bindings. Triggers are the ones due to which function code start executing forex. In the case of HTTP trigger whenever you make HTTP request by hitting the function URL the specific function will start its execution. The Azure function must have only one trigger. Bindings are the direction of data coming in or going out from the function. We have In, out, and both types of bindings.

So for our application, we are creating HTTP Trigger function which takes data and sends it into the Queue. To connect with the queue we need a connection string . We will use Azure service bus client to send message . So let’s navigate to Service bus resource in portal > Shared Access Policy > Copy the Primary Connection String under RootManagedSharedAccessKey

Add below Namespace from the Nuget packet. The above function will post the message to the Queue .
SenderFunction.cs

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Azure.Messaging.ServiceBus;
namespace AzureFunctionPOC
{
    public static class SenderFunction
    {
        [FunctionName("SenderFunction")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "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;
             // Read the connection string from configurations
            string connectionstring= Environment.GetEnvironmentVariable("asbconnectionstring");

             // Initialize Service bus connection 
            ServiceBusClient serviceBusClient = new ServiceBusClient(connectionstring);

             // Initialize a sender object with queue name
            var sender = serviceBusClient.CreateSender("queueforazurefunction");

             // Create message for service bus 
            ServiceBusMessage message = new ServiceBusMessage(requestBody);

             // Send the Message 
            await sender.SendMessageAsync(message);

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

Local.settings.json

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "asbconnectionstring":"Endpoint=sb://processmessage.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=25DPsoiw***********************************"
  }
}

Sender function is ready to test . Lets run the function app on Local and post a request to the queue. Press F5 or start debugging the function app project.

Paste the URL in postman with a request body to post in service bus queue as seen in below screenshot. Click on send button.

This will push the data in to the queue. Lets navigate to service bus explorer .
Open the service bus > Queue > service bus explorer .

Click on peek from start .

We can see the message we posted from Postman as seen in above screenshot.
Sender azure function is ready , Lets move on to the receiver function .
Add a new azure function in the existing VS solution .

ListenerFunction.cs

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

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

There are 2 parameters for Service bus trigger queue name and connection string.
Lets build and run the function app project .

The listener function will trigger as there was a message already pending in the queue we sent using the sender function.
As seen in above screenshot the request posted to queue is now processed and logged in console.
Lets navigate to azure service bus queue and click on peek from start. Queue will be cleared as there wont be any active message.

This is how we can use azure functions to send and receive message to a queue.
Thank you for reading ……… Hope it helps!

Original Post https://msdynamicscrm137374033.wordpress.com/2022/12/11/send-and-receive-messages-to-an-azure-service-bus-queue-from-an-azure-function/

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Join Us
  • X Network2.1K
  • LinkedIn3.8k
  • Bluesky0.5K
Support The Site
Events
March 2025
MTWTFSS
      1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31       
« Feb   Apr »
Follow
Sign In/Sign Up Sidebar Search
Popular Now
Loading

Signing-in 3 seconds...

Signing-up 3 seconds...