如何使用 C++ 的佇列儲存體How to use Queue Storage from C++

提示

Microsoft Azure 儲存體總管Try the Microsoft Azure Storage Explorer

Microsoft Azure 儲存體總管 是一個免費的獨立應用程式,可讓您在 Windows、MacOS 和 Linux 上以視覺化方式處理 Azure 儲存體資料。Microsoft 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 + + 1.0.0 版和更新版本的 Azure 儲存體用戶端程式庫。This guide targets the Azure Storage client library for C++ v1.0.0 and above. 建議的版本是 Azure 儲存體用戶端程式庫 v 2.2.0,可透過 NuGetGitHub取得。The recommended version is Azure Storage client library v2.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 佇列服務元件

  • 儲存體帳戶: 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.windows.net/<queue>URL format: Queues are addressable using the following URL format: http://<storage account>.queue.core.windows.net/<queue>

    下列 URL 可定址圖中的佇列:The following URL addresses a queue in the diagram:

    http://myaccount.queue.core.windows.net/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,或 Azure Storage Resource Provider for .NET 來建立 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

在您想要使用 Azure 儲存體 Api 來存取佇列的 c + + 檔案頂端,加入下列 include 語句: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. 在用戶端應用程式中執行時,您必須提供下列格式的儲存體連接字串:使用儲存體帳戶的名稱,以及針對和值的 Azure 入口網站 中所列出儲存體帳戶的儲存體存取金鑰 AccountName AccountKeyWhen 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"));

若要在本機 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 Azure Blob Storage and Queue Storage 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_message可以從字串 (utf-8 格式) 或位元組陣列建立。A cloud_queue_message can be created from either a string (in UTF-8 format) or a byte array. 以下程式碼會建立佇列 ((如果不存在)) 並插入訊息 Hello, WorldHere 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_messageYou 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 multistep 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: Dequeue the next message

您的程式碼可以使用兩個步驟來清除佇列訊息。Your code dequeues 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_message 處理完訊息之後立即呼叫。Your 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: Use additional options for dequeuing 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. 它也會將可見度逾時設定為每個訊息五分鐘。It also sets the invisibility timeout to five minutes for each message. 請注意,系統會同時為所有訊息啟動五分鐘的時間,因此,從呼叫以來經過五分鐘後 get_messages ,任何尚未刪除的訊息都會重新顯示。Note that the five minutes starts for all messages at the same time, so after five 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 returns queue properties 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_exists 在佇列物件上呼叫方法。To 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.