Exploring Azure Service Bus and Azure Queue Storage Queues

We can develop message-based solutions using either Service Bus or Queue Storage Queues

Microsoft.Azure.ServiceBus
Microsoft.Azure.Storage.Common
Microsoft.Azure.Storage.Queue
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Queue;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using VelidaMessagr.Helpers;
[assembly: FunctionsStartup(typeof(Startup))]
namespace VelidaMessagr.Helpers
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddLogging(loggingBuilder =>
{
loggingBuilder.AddFilter(level => true);
});
var config = new ConfigurationBuilder().
SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
builder.Services.AddSingleton<IConfiguration>(config);// Setting up our Topic Client
builder.Services.AddSingleton(s => new TopicClient(config["ServiceBusConnectionString"], config["TopicName"]));
// Setting up our Subscription client
builder.Services.AddSingleton(s => new SubscriptionClient(config["ServiceBusConnectionString"], config["TopicName"], config["SubscriptionName"]));
// Setting up our Cloud Storage Queue Client
var storageAccount = CloudStorageAccount.Parse(config["StorageConnectionString"]);
builder.Services.AddSingleton((s) => storageAccount.CreateCloudQueueClient());
}
}
}
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.ServiceBus;
using Bogus;
using VelidaMessagr.Models;
using System.Collections.Generic;
using System.Text;
namespace VelidaMessagr.Functions
{
public class PostMessageToServiceBus
{
private readonly ILogger<PostMessageToServiceBus> _logger;
private readonly TopicClient _topicClient;
public PostMessageToServiceBus(
ILogger<PostMessageToServiceBus> logger,
TopicClient topicClient)
{
_logger = logger;
_topicClient = topicClient;
}
[FunctionName("PostMessageToServiceBus")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "ServiceBus")] HttpRequest req)
{
IActionResult result = null;
try
{
// Generate fake readings
var fakeReadings = new Faker<DeviceReading>()
.RuleFor(i => i.ReadingId, (fake) => Guid.NewGuid().ToString())
.RuleFor(i => i.Temperature, (fake) => Math.Round(fake.Random.Decimal(0.00m, 150.00m), 2))
.RuleFor(i => i.Location, (fake) => fake.PickRandom(new List<string> { "New Zealand", "United Kingdom", "Canada" }))
.Generate(10);
foreach (var reading in fakeReadings)
{
var jsonPayload = JsonConvert.SerializeObject(reading);
var message = new Message(Encoding.UTF8.GetBytes(jsonPayload));
await _topicClient.SendAsync(message);
_logger.LogInformation($"Sending message: {jsonPayload}");
}
result = new OkResult();
}
catch (Exception ex)
{
_logger.LogError($"Exception thrown: {ex.Message}");
result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
return result;
}
}
}
subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
{
// Handling our message
}
subscriptionClient.RegisterMessageHandler(ProcessMessageAsync, messageHandlerOptions);subscriptionClient.CloseAsync();
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.Storage.Queue;
using VelidaMessagr.Models;
using Bogus;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace VelidaMessagr.Functions
{
public class PostMessageToQueue
{
private readonly ILogger<PostMessageToQueue> _logger;
private readonly CloudQueueClient _cloudQueueClient;
private readonly IConfiguration _config;
public PostMessageToQueue(
ILogger<PostMessageToQueue> logger,
CloudQueueClient cloudQueueClient,
IConfiguration config)
{
_logger = logger;
_cloudQueueClient = cloudQueueClient;
_config = config;
}
[FunctionName("PostMessageToQueue")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "QueueClient")] HttpRequest req)
{
IActionResult actionResult = null;
try
{
// Generate fake readings
var fakeReadings = new Faker<DeviceReading>()
.RuleFor(i => i.ReadingId, (fake) => Guid.NewGuid().ToString())
.RuleFor(i => i.Temperature, (fake) => Math.Round(fake.Random.Decimal(0.00m, 150.00m), 2))
.RuleFor(i => i.Location, (fake) => fake.PickRandom(new List<string> { "New Zealand", "United Kingdom", "Canada" }))
.Generate(10);
CloudQueue queue = _cloudQueueClient.GetQueueReference(_config["QueueName"]);queue.CreateIfNotExists();foreach (var reading in fakeReadings)
{
var jsonPayload = JsonConvert.SerializeObject(reading);
CloudQueueMessage cloudQueueMessage = new CloudQueueMessage(jsonPayload);
queue.AddMessage(cloudQueueMessage);
}
actionResult = new OkResult();
}
catch (Exception ex)
{
_logger.LogError($"Exception thrown: {ex.Message}");
actionResult = new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
return actionResult;
}
}
}
// Get our messages in a List
List<CloudQueueMessage> messages = (queue.PeekMessages((int)cachedMessageCount)).ToList();
// Iterate through our list
foreach (CloudQueueMessage peekedMessage in messages)
{
Console.WriteLine($"Message: {peekedMessage.AsString}");
}
// Get our messages in a List
List<CloudQueueMessage> messages = (queue.PeekMessages((int)cachedMessageCount)).ToList();
// Iterate through our list
foreach (CloudQueueMessage message in messages)
{
Console.WriteLine($"Message: {message.AsString}");
queue.DeleteMessage(message);
}

--

--

Customer Engineer at Microsoft working in the Fast Track for Azure team. GitHub: https://github.com/willvelida

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store