如何通过 Node.js 使用 Azure 队列存储How to use Azure Queue Storage from Node.js

概述Overview

本指南展示了如何使用 Azure 队列存储完成常见方案。This guide shows you how to accomplish common scenarios using Azure Queue Storage. 相关示例是使用 Node.js API 编写的。The samples are written using the Node.js API. 涵盖的方案包括插入、速览、获取和删除队列消息。The scenarios covered include inserting, peeking, getting, and deleting queue messages. 还将学习创建和删除队列。Also learn to create and delete queues.

什么是队列存储?What is Queue storage?

Azure 队列存储是一项可存储大量消息的服务,用户可以通过经验证的呼叫,使用 HTTP 或 HTTPS 从世界任何地方访问这些消息。Azure Queue storage is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. 一条队列消息的大小最多可为 64 KB,一个队列中可以包含数百万条消息,直至达到存储帐户的总容量限值。A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, up to the total capacity limit of a storage account. 队列存储通常用于创建要异步处理的积压工作 (backlog)。Queue storage is often used to create a backlog of work to process asynchronously.

队列服务概念Queue service concepts

Azure 队列服务包含以下组件:The Azure Queue service contains the following components:

Azure 队列服务组件

  • 存储帐户: 对 Azure 存储进行的所有访问都要通过存储帐户完成。Storage Account: All access to Azure Storage is done through a storage account. 有关存储帐户的详细信息,请参阅存储帐户概述For more information about storage accounts, see Storage account overview.

  • 队列: 一个队列包含一组消息。Queue: A queue contains a set of messages. 所有消息必须位于相应的队列中。All messages must be in a queue. 请注意,队列名称必须全部小写。Note that the queue name must be all lowercase. 有关命名队列的信息,请参阅 命名队列和元数据For information on naming queues, see Naming Queues and Metadata.

  • 消息: 一条消息(无论哪种格式)的最大大小为 64 KB。Message: A message, in any format, of up to 64 KB. 消息可以保留在队列中的最长时间为 7 天。The maximum time that a message can remain in the queue is 7 days. 在 2017-07-29 或更高版本中,最大生存时间可以是任何正数,或者是 -1(表示消息不会过期)。For version 2017-07-29 or later, the maximum time-to-live can be any positive number, or -1 indicating that the message doesn't expire. 如果省略此参数,则默认的生存时间为 7 天。If this parameter is omitted, the default time-to-live is seven days.

  • URL 格式: 使用以下 URL 格式对队列进行寻址: http://<storage account>.queue.core.chinacloudapi.cn/<queue>URL format: Queues are addressable using the following URL format: http://<storage account>.queue.core.chinacloudapi.cn/<queue>

    可使用以下 URL 访问示意图中的某个队列:The following URL addresses a queue in the diagram:

    http://myaccount.queue.core.chinacloudapi.cn/incoming-orders

创建 Azure 存储帐户Create an Azure storage account

创建第一个 Azure 存储帐户的最简单方法是使用 Azure 门户The easiest way to create your first Azure storage account is by using the Azure portal. 若要了解更多信息,请参阅 创建存储帐户To learn more, see Create a storage account.

还可使用 Azure PowerShellAzure CLI适用于 .NET 的 Azure 存储资源提供程序创建 Azure 存储帐户。You can also create an Azure storage account by using Azure PowerShell, Azure CLI, or the Azure Storage Resource Provider for .NET.

如果暂时不想在 Azure 中创建存储帐户,也可以使用 Azurite 存储模拟器在本地环境中运行和测试代码。If you prefer not to create a storage account in Azure at this time, you can also use the Azurite storage emulator to run and test your code in a local environment. 有关详细信息,请参阅使用 Azurite 模拟器进行本地 Azure 存储开发For more information, see Use the Azurite emulator for local Azure Storage development.

创建 Node.js 应用程序Create a Node.js application

若要创建空白的 Node.js 应用程序,请参阅在 Azure 应用服务中创建 Node.js Web 应用构建 Node.js 应用程序并将其部署到 Azure 云服务(使用 PowerShell 或 Visual Studio Code)。To create a blank Node.js application, see Create a Node.js web app in Azure App Service, build and deploy a Node.js application to Azure Cloud Services using PowerShell or Visual Studio Code.

配置应用程序以访问存储Configure your application to access storage

用于 JavaScript 的 Azure 存储客户端库包括一组便于与存储 REST 服务通信的库。The Azure Storage client library for JavaScript includes a set of convenience libraries that communicate with the storage REST services.

使用 Node 包管理器 (npm) 获取包Use Node package manager (npm) to obtain the package

  1. 使用 PowerShell (Windows)、Terminal (Mac) 或 Bash (Unix) 等命令行界面,导航到在其中创建了示例应用程序的文件夹。Use a command-line interface such as PowerShell (Windows), Terminal (Mac), or Bash (Unix), navigate to the folder where you created your sample application.
  1. 在命令窗口中键入 npm install @azure/storage-queueType npm install @azure/storage-queue in the command window.

  2. 验证是否已创建 node_modules 文件夹。Verify that a node_modules folder was created. 在该文件夹中,你会发现 @azure/storage-queue 包,其中包含访问存储所需的客户端库。Inside that folder you'll find the @azure/storage-queue package, which contains the client library you need to access storage.

导入包Import the package

使用你的代码编辑器,将以下内容添加到要在其中使用队列的 JavaScript 文件的顶部。Using your code editor, add the following to the top the JavaScript file where you intend to use queues.

const { QueueClient, QueueServiceClient } = require("@azure/storage-queue");

如何创建队列How to create a queue

以下代码获取名为 AZURE_STORAGE_CONNECTION_STRING 的环境变量的值并使用它创建一个 QueueServiceClient 对象。The following code gets the value of an environment variable called AZURE_STORAGE_CONNECTION_STRING and uses it to create a QueueServiceClient object. 然后,将使用此对象创建一个 QueueClient 对象,后者用于处理特定队列。This object is then used to create a QueueClient object that allows you to work with a specific queue.

// Retrieve the connection from an environment
// variable called AZURE_STORAGE_CONNECTION_STRING
const connectionString = process.env.AZURE_STORAGE_CONNECTION_STRING;

// Create a unique name for the queue
const queueName = "myqueue-" + Date.now().toString();

console.log("Creating queue: ", queueName);

// Instantiate a QueueServiceClient which will be used
// to create a QueueClient and to list all the queues
const queueServiceClient = QueueServiceClient.fromConnectionString(connectionString);

// Get a QueueClient which will be used
// to create and manipulate a queue
const queueClient = queueServiceClient.getQueueClient(queueName);

// Create the queue
await queueClient.create();

如果队列已存在,则会引发异常。If the queue already exists, an exception is thrown.

如何在队列中插入消息How to insert a message into a queue

若要向队列添加消息,请调用 sendMessage 方法。To add a message to a queue, call the sendMessage method.

messageText = "Hello, World";
console.log("Adding message to the queue: ", messageText);

// Add a message to the queue
await queueClient.sendMessage(messageText);

如何速览下一条消息How to peek at the next message

可以通过调用 peekMessages 方法来速览队列中的消息,而不必将其从队列中删除。You can peek at messages in the queue without removing them from the queue by calling the peekMessages method.

默认情况下, peekMessages 扫视单条消息。By default, peekMessages peeks at a single message. 以下示例速览队列中的前五条消息。The following example peeks at the first five messages in the queue. 如果可见消息少于五条,则只返回这些可见消息。If fewer than five messages are visible, just the visible messages are returned.

// Peek at messages in the queue
const peekedMessages = await queueClient.peekMessages({ numberOfMessages: 5 });

for (i = 0; i < peekedMessages.peekedMessageItems.length; i++) {
    // Display the peeked message
    console.log("Peeked message: ", peekedMessages.peekedMessageItems[i].messageText);
}

当队列中没有消息时,调用 peekMessages 不会返回错误。Calling peekMessages when there are no messages in the queue won't return an error. 但是,不会返回消息。However, no messages are returned.

如何更改已排队消息的内容How to change the contents of a queued message

以下示例将更新消息的文本。The following example updates the text of a message.

通过调用 updateMessage 在队列中就地更改消息的内容。Change the contents of a message in-place in the queue by calling updateMessage.

// Get the first message in the queue
var receivedMessages = await queueClient.receiveMessages();
const firstMessage = receivedMessages.receivedMessageItems[0];

// Update the received message
await queueClient.updateMessage(
    firstMessage.messageId,
    firstMessage.popReceipt,
    "This message has been updated"
);

如何将消息取消排队How to dequeue a message

将消息取消排队是一个两阶段过程:Dequeueing a message is a two-stage process:

  1. 获取消息。Get the message.

  2. 删除消息。Delete the message.

以下示例获取一条消息,然后将其删除。The following example gets a message, then deletes it.

若要获取消息,请调用 receiveMessages 方法。To get a message, call the receiveMessages method. 此调用会使消息在队列中不可见,使其他客户端无法处理它们。This call makes the messages invisible in the queue, so no other clients can process them. 当应用程序处理完某条消息后,请调用 deleteMessage 将其从队列中删除。Once your application has processed a message, call deleteMessage to delete it from the queue.

// Get next message from the queue
receivedMessages = await queueClient.receiveMessages();
var message = receivedMessages.receivedMessageItems[0];

console.log("Dequeuing message: ", message.messageText);

await queueClient.deleteMessage(message.messageId, message.popReceipt);

默认情况下,消息只会隐藏 30 秒。By default, a message is only hidden for 30 seconds. 30 秒后,其他客户端就会看到它。After 30 seconds it's visible to other clients. 调用 receiveMessages 时,可以通过设置 options.visibilityTimeout 指定一个不同的值。You can specify a different value by setting options.visibilityTimeout when you call receiveMessages.

当队列中没有消息时,调用 receiveMessages 不会返回错误。Calling receiveMessages when there are no messages in the queue won't return an error. 但是,不会返回消息。However, no messages will be returned.

用于取消对消息进行排队的其他选项Additional options for dequeuing messages

可以通过两种方式自定义队列中的消息检索:There are two ways you can customize message retrieval from a queue:

以下示例使用 receiveMessages 方法在一次调用中获取 5 条消息。The following example uses the receiveMessages method to get five messages in one call. 然后,使用 for 循环处理每条消息。Then it processes each message using a for loop. 它还会将通过此方法返回的所有消息的不可见性超时设置为 5 分钟。It also sets the invisibility timeout to five minutes for all messages returned by this method.

// Get up to 5 messages from the queue
const receivedMsgsResp = await queueClient.receiveMessages({ numberOfMessages: 5, visibilityTimeout: 5 * 60 });

for (i = 0; i < receivedMsgsResp.receivedMessageItems.length; i++)
{
    message = receivedMsgsResp.receivedMessageItems[i];
    console.log("Dequeuing message: ", message.messageText);
    await queueClient.deleteMessage(message.messageId, message.popReceipt);
}

如何获取队列长度How to get the queue length

getProperties 方法返回有关队列的元数据,其中包括在队列中等待的消息的大致数目。The getProperties method returns metadata about the queue, including the approximate number of messages waiting in the queue.

const properties = await queueClient.getProperties();
console.log("Approximate queue length: ", properties.approximateMessagesCount);

如何列出队列How to list queues

若要检索队列的列表,请调用 QueueServiceClient.listQueuesTo retrieve a list of queues, call QueueServiceClient.listQueues. 若要检索按特定前缀筛选的列表,请在调用 listQueues 时设置 options.prefixTo retrieve a list filtered by a specific prefix, set options.prefix in your call to listQueues.

for await (const item of queueServiceClient.listQueues()) {
  console.log("Queue: ", item.name);
}

如何删除队列How to delete a queue

若要删除队列及其包含的所有消息,请对 QueueClient 对象调用 DeleteQueue 方法。To delete a queue and all the messages contained in it, call the DeleteQueue method on the QueueClient object.

// Delete the queue
console.log("Deleting queue: ", queueClient.name);
await queueClient.delete();

若要清除队列中的所有消息而不删除该队列,请调用 ClearMessagesTo clear all messages from a queue without deleting it, call ClearMessages.

提示

查看 Azure 存储代码示例存储库Check out the Azure Storage code samples repository

如需易用且能够下载和运行的端到端 Azure 存储代码示例,请查看我们的 Azure 存储示例列表。For easy-to-use end-to-end Azure Storage code samples that you can download and run, please check out our list of Azure Storage Samples.

后续步骤Next steps

现在,你已了解了有关队列存储的基础知识,请单击下面的链接来了解更复杂的存储任务。Now that you've learned the basics of Queue Storage, follow these links to learn about more complex storage tasks.

访问 GitHub 上的用于 JavaScript 的 Azure 存储客户端库存储库Visit the Azure Storage client library for JavaScript repository on GitHub