Introduction
Azure Service Bus acts as a dependable communication system within the world of cloud computing, enabling secure and reliable interactions between various applications and services.
Compared to other messaging systems, Azure Service Bus offers advanced functionalities. It provides a great framework for different components of an application to communicate effectively and securely.
Using Azure Service Bus involves setting up communication between applications and services. You can create these pathways, send messages between them, and configure how messages are handled.
Throughout this discussion, we'll dive into the features and capabilities of the Service Bus and explore how it can be effectively utilized in diverse applications and scenarios.
You will need an Azure account. I invite you to create your first Azure account by clicking on this link.
Throughout your reading, you will see how to:
- Send messages in a queue,
- Consume messages in a queue,
- Send messages using topics,
- Subscribe to a topic and receive messages,
Regarding the code, most of the calls will be non-blocking and therefore asynchronous; a good understanding of async is essential, you can find more info about it here.
Azure Service Bus — Overview
Azure Service Bus facilitates the separation of data with a focus on both reliability and security.
Azure Service Bus provides us with the ability to leverage various scenarios:
- Sending messages in a Queue,
- Decoupling applications for improved reliability and greater scalability
We know that Azure Storage Queue allows:
- Storing over 80GB of messages in a queue,
- Tracking message processing progress,
- Accessing activity logs,
Although Azure Service Bus doesn't have these three advantages, it offers compelling functionalities that aren't available at the Azure Service Queue level:
- Receiving messages without needing to query the queue,
- A 1-to-N relationship between publishers and subscribers through Topics,
- Implementing workflow coordination and multiplexed transfers that require strict message ordering or message deferral,
- Service Bus ensures FIFO (First In First Out),
- Support for the AMQP protocol and other features,
The First In, First Out (FIFO) principle is a method used in queue management, where the first item to enter the queue is the first to be processed or serviced, following a sequential order. This principle ensures that items or elements are processed or dealt with in the same order they were received, without any prioritization or reordering based on urgency or importance. It's a fundamental concept in managing queues and is commonly used in various computing and business scenarios where order preservation is critical.
If you find yourself in any of the mentioned scenarios, Azure Service Bus is your ally.
Azure Service Bus is a fully managed enterprise message broker with message queues and publish-subscribe topics (in a namespace). Service Bus is used to decouple applications and services from each other. <
Azure Service Bus — Queues
The queues will allow us to store the sent messages until the consumer requests them for processing. Below is what a Queue looks like.
In summary, a queue is:
- A temporary storage warehouse for messages,
- Messages are delivered upon the consumer's request,
- The receiver consumes messages starting with the one that arrived first, following the First In First Out principle.
Example of Use
We have two services:
- The first service creates users.
- The second service handles notifications, sending emails and/or push notifications to our users after their creation.
In our example, it is possible to subscribe our notification service to the 'notification' queue, which receives messages such as 'UserCreated' with the property 'UserId = xxx'. This identifier will be used by the notification service to send a welcome email.
Azure Service Bus — Topics
Topics provide the ability to have a provider with multiple observers or consumers, each consumer having its own queue that feeds it.
Example of Use
Let's consider the following scenario:
- A user creation service
- Several microservices (notification microservice, articles microservice, product microservice, etc.)
In our case, upon creating a new user, the service will notify through a topic to different subscribers/microservices about the creation of a new user. This allows other services to:
- Send the user a confirmation of the account creation,
- Add the user's identifier in the schema of the Article microservice's database to send them new articles,
- Add the user's identifier in the schema of the Product microservice's database to notify them about promotions, new products, etc.
In practice?
-
Sign in to Azure Portal:
- Go to portal.azure.com and log in to your Azure account.
-
Create a new Service Bus namespace:
- Click on "+ Create a resource."
- Search for "Service Bus" and select it.
- Fill in details for the new namespace (subscription, resource group, name, region, and SKU).
- Click "Review + Create," then "Create" to start deployment.
-
Review and deploy:
- Review configuration details and initiate the deployment process.
- Wait for the deployment to complete.
-
Access your Service Bus:
- Once deployed, find your Service Bus namespace under "All resources."
- Explore and manage your Service Bus, create queues, topics, or subscriptions as needed.
Within your Service Bus namespace, you can create queues, topics, subscriptions, and manage various settings based on your application needs.
Click on "Queues" or "Topics" to create a new queue or topic and set up subscriptions or rules according to your messaging requirements.
Creating Queues
import { ServiceBusClient } from '@azure/service-bus';
async function createQueue() {
const connectionString = '<YOUR_CONNECTION_STRING>'; // Replace with your Service Bus connection string
const queueName = '<YOUR_QUEUE_NAME>'; // Replace with your desired queue name
const serviceBusClient = new ServiceBusClient(connectionString);
try {
const queueOptions = {
// Define queue options if needed
// For example:
// defaultMessageTimeToLive: 60 // Message time-to-live in seconds
};
const queueDetails = await serviceBusClient.createQueue(queueName, queueOptions);
console.log(`Queue "${queueDetails.queueName}" created successfully.`);
} catch (error) {
console.error('Error creating queue:', error);
} finally {
await serviceBusClient.close();
}
}
// Call the function to create the queue
createQueue();
Sending a message
const { ServiceBusClient } = require('@azure/service-bus');
async function sendMessageToQueue() {
const connectionString = '<YOUR_CONNECTION_STRING>'; // Replace with your Service Bus connection string
const queueName = '<YOUR_QUEUE_NAME>'; // Replace with your queue name
const serviceBusClient = new ServiceBusClient(connectionString);
try {
const sender = serviceBusClient.createSender(queueName);
const message = {
body: 'Hello, Azure Service Bus!', // Replace with your message payload
};
await sender.sendMessages(message);
console.log('Message sent successfully to the queue.');
} catch (error) {
console.error('Error sending message:', error);
} finally {
await serviceBusClient.close();
}
}
// Call the function to send the message
sendMessageToQueue();
This JavaScript code uses the ServiceBusClient class from the @azure/service-bus package to create a sender for the specified queue and sends a message with a simple payload, and the ServiceBusClient package to create a sender for the specified queue.
Adjust the message body or other properties as needed based on your requirements.
Make sure to handle errors appropriately and ensure that your Azure account has the necessary permissions to send messages to the specified queue in the Service Bus namespace.
This process sets up a basic Azure Service Bus namespace. From there, you can integrate it into your applications, set up messaging patterns, and utilize the Service Bus functionalities to facilitate communication between different components of your applications or services.
Conclusion
Throughout this article, we've covered the creation and receipt of messages within and from a queue.
This service broadens the spectrum of possibilities significantly. One can envision utilizing queues within Azure Functions to trigger processes upon message receipt.
I hope this article has allowed you to familiarize yourself with Azure Service Bus, and please leave a comment if you have any questions.
Top comments (0)