Azure App Service - Web App - Azure Service Bus

62 Views Asked by At

I would like to consume Azure Service Bus Queue message from .NET core REST api.

I can do it locally on my laptop as I can manually run the API to consume the message.

After deploying this rest api as web app on Azure App Services..... How my WEB App will know, the message in "Azure service bus queue" is arrived and need to consume the same.

Note:

  1. I know this can be done using Azure Function - Service Bus Trigger
  2. I m more interested in Microservices - Producer - Consumer point of view
  3. Queue system could be Azure Service bus / RabbitMQ / Kafka etc

Tried to find on web, not got anything good.

1

There are 1 best solutions below

0
SiddheshDesai On

You can implement the Peek message Function to just read the message without removing it from the service bus queue in your .net core API:-

Peek message queue sample:-

Program.cs:-

using Azure.Messaging.ServiceBus;
using Newtonsoft.Json;
using ServiceBusQueue;

string connectionString = "Endpoint=sb://siliconsb54.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=R0hMdUwLTUm1+aIfJbuYURsHEtqkjCSqM+ASbJttxpM=";
string queueName = "myqueue";

List<Order> orders = new List<Order>()
{
        new Order(){OrderID="01",Quantity=100,UnitPrice=9.99F},
        new Order(){OrderID="02",Quantity=200,UnitPrice=10.99F},
        new Order(){OrderID="03",Quantity=300,UnitPrice=8.99F}

};

// await SendMessage(orders);

await PeekMessages();


async Task SendMessage(List<Order> orders)
{
    ServiceBusClient serviceBusClient=new ServiceBusClient(connectionString);
    ServiceBusSender serviceBusSender= serviceBusClient.CreateSender(queueName);

    ServiceBusMessageBatch serviceBusMessageBatch = await serviceBusSender.CreateMessageBatchAsync();
    foreach(Order order in orders)
    {

        ServiceBusMessage serviceBusMessage = new ServiceBusMessage(JsonConvert.SerializeObject(order));
        serviceBusMessage.ContentType = "application/json";
        if (!serviceBusMessageBatch.TryAddMessage(
            serviceBusMessage))
        {
            throw new Exception("Error occured");
        }
            
    }
    Console.WriteLine("Sending messages");
    await serviceBusSender.SendMessagesAsync(serviceBusMessageBatch);
}

async Task PeekMessages()
{
    ServiceBusClient serviceBusClient = new ServiceBusClient(connectionString);
    ServiceBusReceiver serviceBusReceiver = serviceBusClient.CreateReceiver(queueName,
        new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock });

    IAsyncEnumerable<ServiceBusReceivedMessage> messages=serviceBusReceiver.ReceiveMessagesAsync();

    await foreach(ServiceBusReceivedMessage message in messages)
    {
        Order order = JsonConvert.DeserializeObject<Order>(message.Body.ToString());
        Console.WriteLine("Order Id {0}", order.OrderID);
        Console.WriteLine("Quantity {0}", order.Quantity);
        Console.WriteLine("Unit Price {0}", order.UnitPrice);

    }
}

Given my Order.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServiceBusQueue
{
    public class Order
    {
        public string OrderID { get; set; }
        public int Quantity { get; set; }
        public float UnitPrice { get; set; }

    }
}

You can also make use of Azure Functions directly and it will be triggered as soon as your service bus queue receives new message:-

Function1.cs:-

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

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

enter image description here