This tutorial demonstrates how to send a message to an Azure Storage Queue using the Azure SDKs. Azure Storage Queues provide a reliable way to decouple application components and manage asynchronous operations.
If you don't have a storage account and a queue, you can create them using the Azure portal or Azure CLI.
Log in to your Azure account:
az login
Create a resource group (if you don't have one):
az group create --name myResourceGroup --location eastus
Create a storage account:
az storage account create --name mystorageaccount --resource-group myResourceGroup --location eastus --sku Standard_LRS
Replace mystorageaccount with a unique name.
Create a queue:
az storage queue create --name myqueue --account-name mystorageaccount --account-key <your_storage_account_key>
You can get your storage account key using az storage account keys list --account-name mystorageaccount --resource-group myResourceGroup --query "[0].value" -o tsv.
We'll use the @azure/storage-queue package for this tutorial. Open your terminal in your project directory and run:
npm install @azure/storage-queue
Create a JavaScript file (e.g., sendMessage.js) and add the following code. You'll need your storage account name and account key (or a connection string).
// sendMessage.js
import { QueueClient } from "@azure/storage-queue";
async function sendMessageToQueue() {
const accountName = "";
const accountKey = "";
const queueName = "myqueue"; // Make sure this matches your queue name
// Construct the connection string
const connectionString = `DefaultEndpointsProtocol=https;AccountName=${accountName};AccountKey=${accountKey};EndpointSuffix=core.windows.net`;
// Create a QueueClient
const queueClient = new QueueClient(connectionString, queueName);
const messageText = "Hello from Azure Storage Queue Tutorial!";
try {
// Send the message
const result = await queueClient.sendMessage(messageText);
console.log(`Message sent successfully. Message ID: ${result.messageId}`);
// Optionally, you can also send a message with TTL and visibility timeout
const messageWithParams = "This message has custom parameters.";
const ttl = 60 * 60; // 1 hour in seconds
const visibilityTimeout = 30; // seconds
const resultWithParams = await queueClient.sendMessage(messageWithParams, {
timeToLive: ttl,
visibilityTimeout: visibilityTimeout,
});
console.log(`Message with parameters sent successfully. Message ID: ${resultWithParams.messageId}`);
} catch (error) {
console.error("Error sending message to queue:", error);
}
}
sendMessageToQueue();
Replace <YOUR_STORAGE_ACCOUNT_NAME> and <YOUR_STORAGE_ACCOUNT_KEY> with your actual credentials.
Execute your JavaScript file using Node.js:
node sendMessage.js
If successful, you will see output similar to:
Message sent successfully. Message ID: <some-guid>
Message with parameters sent successfully. Message ID: <another-guid>