如何通过 C++ 使用队列存储How to use Queue Storage from C++

提示

尝试 Azure 存储资源管理器Try the Azure Storage Explorer

Azure 存储资源管理器是 Microsoft 免费提供的独立应用,适用于在 Windows、macOS 和 Linux 上以可视方式处理 Azure 存储数据。Azure Storage Explorer is a free, standalone app from Microsoft that enables you to work visually with Azure Storage data on Windows, macOS, and Linux.

概述Overview

本指南演示如何使用 Azure 队列存储服务执行常见方案。This guide will show you how to perform common scenarios using the Azure Queue storage service. 示例采用 C++ 编写,并使用了适用于 C++ 的 Azure 存储客户端库The samples are written in C++ and use the Azure Storage Client Library for C++. 介绍的方案包括插入扫视获取删除队列消息以及创建和删除队列The scenarios covered include inserting, peeking, getting, and deleting queue messages, as well as creating and deleting queues.

备注

本指南主要面向适用于 C++ 的 Azure 存储客户端库 1.0.0 版及更高版本。This guide targets the Azure Storage Client Library for C++ version 1.0.0 and above. 推荐版本:存储客户端库 2.2.0(可通过 NuGetGitHub 获得)。The recommended version is Storage Client Library 2.2.0, which is available via NuGet or GitHub.

什么是队列存储?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 队列服务组件

  • 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 存储进行的所有访问都要通过存储帐户完成。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.

创建 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.

创建 C++ 应用程序Create a C++ application

在本指南中,将使用存储功能,这些功能可以在 C++ 应用程序中运行。In this guide, you will use storage features which can be run within a C++ application.

为此,需要安装适用于 C++ 的 Azure 存储客户端库,并在 Azure 订阅中创建 Azure 存储帐户。To do so, you will need to install the Azure Storage Client Library for C++ and create an Azure storage account in your Azure subscription.

若要安装适用于 C++ 的 Azure 存储客户端库,可使用以下方法:To install the Azure Storage Client Library for C++, you can use the following methods:

.\vcpkg.exe install azure-storage-cpp

可以在自述文件中找到有关如何生成源代码和导出到 NuGet 的指南。You can find a guide for how to build the source code and export to NuGet in the README file.

配置应用程序以访问队列存储Configure your application to access Queue Storage

将以下 include 语句添加到要在其中使用 Azure 存储 API 来访问队列 C++ 文件的顶部:Add the following include statements to the top of the C++ file where you want to use the Azure storage APIs to access queues:

#include <was/storage_account.h>
#include <was/queue.h>

设置 Azure 存储连接字符串Set up an Azure storage connection string

Azure 存储客户端使用存储连接字符串来存储用于访问数据管理服务的终结点和凭据。An Azure storage client uses a storage connection string to store endpoints and credentials for accessing data management services. 在客户端应用程序中运行时,必须提供以下格式的存储连接字符串,并对 AccountName 和 AccountKey 值使用 Azure 门户中列出的存储帐户的名称和存储帐户的存储访问密钥。When running in a client application, you must provide the storage connection string in the following format, using the name of your storage account and the storage access key for the storage account listed in the Azure Portal for the AccountName and AccountKey values. 有关存储帐户和访问密钥的信息,请参阅关于 Azure 存储帐户For information on storage accounts and access keys, see About Azure Storage Accounts. 此示例演示如何声明一个静态字段以保存连接字符串:This example shows how you can declare a static field to hold the connection string:

// Define the connection-string with your values.
const utility::string_t storage_connection_string(U("DefaultEndpointsProtocol=https;AccountName=your_storage_account;AccountKey=your_storage_account_key;EndpointSuffix=core.chinacloudapi.cn"));

若要在本地 Windows 计算机中测试应用程序,可以使用 Azurite 存储模拟器To test your application in your local Windows computer, you can use the Azurite storage emulator. Azurite 是一种实用工具,用于在本地开发计算机上模拟 Azure 中提供的 Blob 和队列服务。Azurite is a utility that simulates the Blob and Queue services available in Azure on your local development machine. 以下示例演示如何声明一个静态字段以将连接字符串保存到本地存储模拟器:The following example shows how you can declare a static field to hold the connection string to your local storage emulator:

// Define the connection-string with Azurite.
const utility::string_t storage_connection_string(U("UseDevelopmentStorage=true;"));  

若要启动 Azurite,请参阅使用 Azurite 模拟器进行本地 Azure 存储开发To start Azurite, see Use the Azurite emulator for local Azure Storage development.

下面的示例假定使用了这两个方法之一来获取存储连接字符串。The following samples assume that you have used one of these two methods to get the storage connection string.

检索连接字符串Retrieve your connection string

可使用 cloud_storage_account 类来表示存储帐户信息。You can use the cloud_storage_account class to represent your Storage Account information. 若要从存储连接字符串中检索存储帐户信息,可以使用 parse 方法。To retrieve your storage account information from the storage connection string, you can use the parse method.

// Retrieve storage account from connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

如何:创建队列How to: Create a queue

cloud_queue_client 对象可用于获取队列的引用对象。A cloud_queue_client object lets you get reference objects for queues. 以下代码创建 cloud_queue_client 对象。The following code creates a cloud_queue_client object.

// Retrieve storage account from connection string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create a queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

使用 cloud_queue_client 对象可获取对要使用的队列的引用。Use the cloud_queue_client object to get a reference to the queue you want to use. 如果队列不存在,可以创建它。You can create the queue if it doesn't exist.

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// Create the queue if it doesn't already exist.
 queue.create_if_not_exists();  

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

要将消息插入到现有队列中,请先创建新的 cloud_queue_messageTo insert a message into an existing queue, first create a new cloud_queue_message. 接下来,调用 add_message 方法。Next, call the add_message method. 可以从字符串或字节数组创建 cloud_queue_messageA cloud_queue_message can be created from either a string or a byte array. 以下代码将创建队列(如果该队列不存在)并插入消息“Hello, World”:Here is code which creates a queue (if it doesn't exist) and inserts the message 'Hello, World':

// Retrieve storage account from connection-string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// Create the queue if it doesn't already exist.
queue.create_if_not_exists();

// Create a message and add it to the queue.
azure::storage::cloud_queue_message message1(U("Hello, World"));
queue.add_message(message1);  

如何:扫视下一条消息How to: Peek at the next message

通过调用 peek_message 方法,可以速览队列前面的消息,而不必从该队列中将其删除。You can peek at the message in the front of a queue without removing it from the queue by calling the peek_message method.

// Retrieve storage account from connection-string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// Peek at the next message.
azure::storage::cloud_queue_message peeked_message = queue.peek_message();

// Output the message content.
std::wcout << U("Peeked message content: ") << peeked_message.content_as_string() << std::endl;

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

可以更改队列中现有消息的内容。You can change the contents of a message in-place in the queue. 如果消息表示工作任务,可使用此功能来更新该工作任务的状态。If the message represents a work task, you could use this feature to update the status of the work task. 以下代码使用新内容更新队列消息,并将可见性超时设置为再延长 60 秒。The following code updates the queue message with new contents, and sets the visibility timeout to extend another 60 seconds. 这会保存与消息关联的工作的状态,并额外为客户端提供一分钟的时间来继续处理消息。This saves the state of work associated with the message, and gives the client another minute to continue working on the message. 可使用此方法跟踪队列消息上的多步骤工作流,即使处理步骤因硬件或软件故障而失败,也无需从头开始操作。You could use this technique to track multi-step workflows on queue messages, without having to start over from the beginning if a processing step fails due to hardware or software failure. 通常,还可以保留重试计数,如果某条消息的重试次数超过 n,将删除此消息。Typically, you would keep a retry count as well, and if the message is retried more than n times, you would delete it. 这可避免每次处理某条消息时都触发应用程序错误。This protects against a message that triggers an application error each time it is processed.

// Retrieve storage account from connection-string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// Get the message from the queue and update the message contents.
// The visibility timeout "0" means make it visible immediately.
// The visibility timeout "60" means the client can get another minute to continue
// working on the message.
azure::storage::cloud_queue_message changed_message = queue.get_message();

changed_message.set_content(U("Changed message"));
queue.update_message(changed_message, std::chrono::seconds(60), true);

// Output the message content.
std::wcout << U("Changed message content: ") << changed_message.content_as_string() << std::endl;  

如何:取消下一条消息的排队How to: De-queue the next message

代码通过两个步骤来取消对队列中某条消息的排队。Your code de-queues a message from a queue in two steps. 调用 get_message 时,会获得队列中的下一条消息。When you call get_message, you get the next message in a queue. get_message 返回的消息对从此队列读取消息的其他任何代码不可见。A message returned from get_message becomes invisible to any other code reading messages from this queue. 若要完成从队列中删除消息,还必须调用 delete_messageTo finish removing the message from the queue, you must also call delete_message. 此删除消息的两步过程可确保,如果代码因硬件或软件故障而无法处理消息,则代码的其他实例可以获取相同消息并重试。This two-step process of removing a message assures that if your code fails to process a message due to hardware or software failure, another instance of your code can get the same message and try again. 代码在处理消息后会立即调用 delete_messageYour code calls delete_message right after the message has been processed.

// Retrieve storage account from connection-string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// Get the next message.
azure::storage::cloud_queue_message dequeued_message = queue.get_message();
std::wcout << U("Dequeued message: ") << dequeued_message.content_as_string() << std::endl;

// Delete the message.
queue.delete_message(dequeued_message);

如何:使用其他方法取消对消息的排队How to: Leverage additional options for de-queuing messages

可通过两种方式自定义队列中消息的检索。There are two ways you can customize message retrieval from a queue. 首先,可获取一批消息(最多 32 条)。First, you can get a batch of messages (up to 32). 其次,可以设置更长或更短的不可见超时时间,从而允许代码使用更多或更少时间来完全处理每个消息。Second, you can set a longer or shorter invisibility timeout, allowing your code more or less time to fully process each message. 以下代码示例使用 get_messages 方法来在一次调用中获取 20 条消息。The following code example uses the get_messages method to get 20 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 each message. 请注意,将对所有消息同时启动 5 分钟的超时设置,因此调用 get_messages 的 5 分钟后,任何尚未删除的消息都将再次可见。Note that the 5 minutes starts for all messages at the same time, so after 5 minutes have passed since the call to get_messages, any messages which have not been deleted will become visible again.

// Retrieve storage account from connection-string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// Dequeue some queue messages (maximum 32 at a time) and set their visibility timeout to
// 5 minutes (300 seconds).
azure::storage::queue_request_options options;
azure::storage::operation_context context;

// Retrieve 20 messages from the queue with a visibility timeout of 300 seconds.
std::vector<azure::storage::cloud_queue_message> messages = queue.get_messages(20, std::chrono::seconds(300), options, context);

for (auto it = messages.cbegin(); it != messages.cend(); ++it)
{
    // Display the contents of the message.
    std::wcout << U("Get: ") << it->content_as_string() << std::endl;
}

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

可以获取队列中消息的估计数。You can get an estimate of the number of messages in a queue. download_attributes 方法允许队列服务检索队列属性,包括消息计数。The download_attributes method asks the Queue service to retrieve the queue attributes, including the message count. approximate_message_count 方法可获取队列中的大致消息数。The approximate_message_count method gets the approximate number of messages in the queue.

// Retrieve storage account from connection-string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// Fetch the queue attributes.
queue.download_attributes();

// Retrieve the cached approximate message count.
int cachedMessageCount = queue.approximate_message_count();

// Display number of messages.
std::wcout << U("Number of messages in queue: ") << cachedMessageCount << std::endl;  

如何:删除队列How to: Delete a queue

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

// Retrieve storage account from connection-string.
azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string);

// Create the queue client.
azure::storage::cloud_queue_client queue_client = storage_account.create_cloud_queue_client();

// Retrieve a reference to a queue.
azure::storage::cloud_queue queue = queue_client.get_queue_reference(U("my-sample-queue"));

// If the queue exists and delete it.
queue.delete_queue_if_exists();  

后续步骤Next steps

现在,已了解队列存储的基础知识,请打开以下链接了解有关 Azure 存储的详细信息。Now that you've learned the basics of Queue storage, follow these links to learn more about Azure Storage.