以 .NET 開始使用 Azure 佇列儲存體Get started with Azure Queue storage using .NET

提示

請查看 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.

概觀Overview

Azure 佇列儲存體可提供應用程式元件之間的雲端傳訊。Azure Queue storage provides cloud messaging between application components. 設計擴充性的應用程式時,會經常分離應用程式元件,以便進行個別擴充。In designing applications for scale, application components are often decoupled, so that they can scale independently. 佇列儲存體可針對應用程式元件間的通訊,提供非同步傳訊,無論應用程式元件是在雲端、桌面、內部部署伺服器或行動裝置上執行。Queue storage delivers asynchronous messaging for communication between application components, whether they are running in the cloud, on the desktop, on an on-premises server, or on a mobile device. 佇列儲存體也支援管理非同步工作並建置處理工作流程。Queue storage also supports managing asynchronous tasks and building process work flows.

關於本教學課程About this tutorial

本教學課程說明如何使用 Azure 佇列儲存體撰寫一些常見案例的 .NET 程式碼。This tutorial shows how to write .NET code for some common scenarios using Azure Queue storage. 本文說明的案例包括建立和刪除佇列,以及新增、讀取和刪除佇列訊息。Scenarios covered include creating and deleting queues and adding, reading, and deleting queue messages.

預估完成時間: 45 分鐘Estimated time to complete: 45 minutes

必要條件Prerequisites

什麼是佇列儲存體?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.

佇列儲存體的一般用途包括:Common uses of Queue storage include:

  • 建立積存的工作供非同步處理Creating a backlog of work to process asynchronously
  • 將訊息從 Azure Web 角色傳遞至 Azure 背景工作角色Passing messages from an Azure web role to an Azure worker role

佇列服務概念Queue Service Concepts

佇列服務包含下列元件:The Queue service contains the following components:

Queue1

  • URL 格式: 可利用下列 URL 格式來定址佇列:URL format: Queues are addressable using the following URL format:
    http://<storage account>.queue.core.windows.net/<queue>http://<storage account>.queue.core.windows.net/<queue>

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

    http://myaccount.queue.core.windows.net/images-to-download

  • 儲存體帳戶: 所有對 Azure 儲存體的存取都是透過儲存體帳戶進行。Storage Account: All access to Azure Storage is done through a storage account. 如需關於儲存體帳戶容量的詳細資訊,請參閱< Azure 儲存體延展性和效能目標 >(英文)。See Azure Storage Scalability and Performance Targets for details about storage account capacity.

  • 佇列: 佇列包含一組訊息。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.

建立 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 中建立儲存體帳戶,也可以使用 Azure 儲存體模擬器在本機環境中執行並測試您的程式碼。If you prefer not to create a storage account in Azure at this time, you can also use the Azure storage emulator to run and test your code in a local environment. 如需詳細資訊,請參閱 使用 Azure 儲存體模擬器進行開發和測試For more information, see Use the Azure Storage Emulator for Development and Testing.

設定開發環境Set up your development environment

接下來,在 Visual Studio 中設定您的開發環境,以便您開始嘗試本指南中的程式碼範例。Next, set up your development environment in Visual Studio so you're ready to try the code examples in this guide.

建立 Windows 主控台應用程式專案Create a Windows console application project

在 Visual Studio 中,建立新的 Windows 主控台應用程式。In Visual Studio, create a new Windows console application. 下列步驟說明如何在 Visual Studio 2019 中建立主控台應用程式。The following steps show you how to create a console application in Visual Studio 2019. 這些步驟類似其他 Visual Studio 版本中的步驟。The steps are similar in other versions of Visual Studio.

  1. 選取 [檔案] > [新增] > [專案] Select File > New > Project
  2. 選取 平台 > WindowsSelect Platform > Windows
  3. 選取 主控台應用程式 (.NET Framework)Select Console App (.NET Framework)
  4. 選取 [下一步] Select Next
  5. 專案名稱欄位中,輸入您的應用程式的名稱In the Project name field, enter a name for your application
  6. 選取 [建立] Select Create

在本教學課程中的所有程式碼範例,請新增至main () 方法,您的主控台應用程式Program.cs檔案。All code examples in this tutorial can be added to the Main() method of your console application's Program.cs file.

您可以使用 Azure 儲存體用戶端程式庫,在任何類型的.NET 應用程式,包括 Azure 雲端服務或 web 應用程式和桌面和行動應用程式。You can use the Azure Storage client libraries in any type of .NET application, including an Azure cloud service or web app, and desktop and mobile applications. 在本指南中,為求簡化,我們會使用主控台應用程式。In this guide, we use a console application for simplicity.

使用 NuGet 來安裝必要的封裝Use NuGet to install the required packages

您必須參考您的專案,才能完成本教學課程中的下列三個套件:You need to reference the following three packages in your project to complete this tutorial:

您可以使用 NuGet 來取得這些套件。You can use NuGet to obtain these packages. 請遵循下列步驟:Follow these steps:

  1. 在 [方案總管] 中以滑鼠右鍵按一下專案,然後選擇 [管理 NuGet 套件] 。Right-click your project in Solution Explorer, and choose Manage NuGet Packages.
  2. 選取 [瀏覽] Select Browse
  3. 線上搜尋"Microsoft.Azure.Storage.Queue 」,然後選取安裝安裝儲存體用戶端程式庫和其相依性。Search online for "Microsoft.Azure.Storage.Queue", and select Install to install the Storage client library and its dependencies. 這也會安裝 Microsoft.Azure.Storage.Common 程式庫,這是佇列的程式庫的相依性。This will also install the Microsoft.Azure.Storage.Common library, which is a dependency of the queue library.
  4. 線上搜尋"Microsoft.Azure.ConfigurationManager 」,然後選取安裝來安裝 Azure Configuration Manager。Search online for "Microsoft.Azure.ConfigurationManager", and select Install to install the Azure Configuration Manager.

注意

儲存體用戶端程式庫套件也會包含在Azure SDK for.NETThe Storage client libraries packages are also included in the Azure SDK for .NET. 不過,我們建議您也從以確保您永遠有最新版本的 NuGet 安裝儲存體用戶端程式庫。However, we recommend that you also install the Storage client libraries from NuGet to ensure that you always have the latest versions.

適用於.NET 的儲存體用戶端程式庫中的 ODataLib 相依性會解決 ODataLib 套件可用在 NuGet 上而不是從 WCF 資料服務。The ODataLib dependencies in the Storage client libraries for .NET are resolved by the ODataLib packages available on NuGet, not from WCF Data Services. 您可以直接下載 ODataLib 程式庫,或是由您的程式碼專案透過 NuGet 參照這些程式庫。The ODataLib libraries can be downloaded directly, or referenced by your code project through NuGet. 儲存體用戶端程式庫所使用的特定 ODataLib 封裝包括ODataEdm,並空間The specific ODataLib packages used by the Storage client libraries are OData, Edm, and Spatial. 雖然這些程式庫類別所使用的 Azure 資料表儲存體,也就是必要的相依性,使用儲存體用戶端程式庫進行程式設計。While these libraries are used by the Azure Table storage classes, they are required dependencies for programming with the Storage client libraries.

決定您的目標環境Determine your target environment

有兩個環境選項可供您執行本指南中的範例︰You have two environment options for running the examples in this guide:

  • 您可以對雲端中的 Azure 儲存體帳戶執行您的程式碼。You can run your code against an Azure Storage account in the cloud.
  • 您可以對 Azure 儲存體模擬器執行您的程式碼。You can run your code against the Azure storage emulator. 儲存體模擬器是模擬雲端中 Azure 儲存體帳戶的本機環境。The storage emulator is a local environment that emulates an Azure Storage account in the cloud. 模擬器是一個免費選項,在開發您的應用程式時可用於測試和偵錯您的程式碼。The emulator is a free option for testing and debugging your code while your application is under development. 模擬器會使用已知的帳戶和金鑰。The emulator uses a well-known account and key. 如需詳細資訊,請參閱使用 Azure 儲存體模擬器進行開發和測試For more information, see Use the Azure storage emulator for development and testing.

如果您要選擇以雲端中的儲存體帳戶為目標,請從 Azure 入口網站複製您的儲存體帳戶的主要存取金鑰。If you are targeting a storage account in the cloud, copy the primary access key for your storage account from the Azure portal. 如需詳細資訊,請參閱存取金鑰For more information, see Access keys.

注意

您可以選擇以儲存體模擬器為目標,以避免產生與 Azure 儲存體相關聯的任何費用。You can target the storage emulator to avoid incurring any costs associated with Azure Storage. 不過,如果您選擇以雲端中的 Azure 儲存體帳戶為目標,則執行本教學課程的費用可以忽略不計。However, if you do choose to target an Azure storage account in the cloud, costs for performing this tutorial will be negligible.

設定儲存體連接字串Configure your storage connection string

如需使用儲存體連接字串來設定端點與認證以存取儲存體服務的.NET 支援 Azure 儲存體用戶端程式庫。The Azure Storage client libraries for .NET support using a storage connection string to configure endpoints and credentials for accessing storage services. 在組態檔中維護儲存體連接字串是最佳方式。The best way to maintain your storage connection string is in a configuration file.

如需有關連接字串的詳細資訊,請參閱設定 Azure 儲存體的連接字串For more information about connection strings, see Configure a connection string to Azure Storage.

注意

儲存體帳戶金鑰很類似儲存體帳戶的根密碼。Your storage account key is similar to the root password for your storage account. 請務必小心保護您的儲存體帳戶金鑰。Always be careful to protect your storage account key. 請避免轉發給其他使用者、進行硬式編碼,或將它儲存在其他人可以存取的純文字檔案。Avoid distributing it to other users, hard-coding it, or saving it in a plain-text file that is accessible to others. 如果您認為金鑰可能遭到破解,請使用 Azure 入口網站重新產生金鑰。Regenerate your key by using the Azure portal if you believe it may have been compromised.

若要設定您的連接字串,開啟app.config從 Visual Studio 方案總管中的檔案。To configure your connection string, open the app.config file from Solution Explorer in Visual Studio. 新增的內容 <appSettings> 如下所示的項目。Add the contents of the <appSettings> element shown below. 取代帳戶名稱的儲存體帳戶名稱並帳戶金鑰與您的帳戶存取金鑰:Replace account-name with the name of your storage account, and account-key with your account access key:

<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <appSettings>
        <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key" />
    </appSettings>
</configuration>

例如,組態設定會如下顯示:For example, your configuration setting appears similar to:

<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=storagesample;AccountKey=GMuzNHjlB3S9itqZJHHCnRkrokLkcSyW7yK9BRbGp0ENePunLPwBgpxV1Z/pVo9zpem/2xSHXkMqTHHLcx8XRA==" />

若要以儲存體模擬器為目標,您可以使用對應到已知帳戶名稱和金鑰的捷徑。 在此情況下,您的連接字串設定會是︰In that case, your connection string setting is:

<add key="StorageConnectionString" value="UseDevelopmentStorage=true;" />

新增 using 指示詞Add using directives

將下列 using 指示詞新增至 Program.cs 檔案的開頭處:Add the following using directives to the top of the Program.cs file:

using Microsoft.Azure; // Namespace for CloudConfigurationManager
using Microsoft.Azure.Storage; // Namespace for CloudStorageAccount
using Microsoft.Azure.Storage.Queue; // Namespace for Queue storage types

從 Azure 入口網站複製您的認證Copy your credentials from the Azure portal

範例程式碼需要授與對您儲存體帳戶的存取權。The sample code needs to authorize access to your storage account. 若要進行授權,您必須以連接字串的形式為應用程式提供您的儲存體帳戶認證。To authorize, you provide the application with your storage account credentials in the form of a connection string. 若要檢視您的儲存體帳戶認證:To view your storage account credentials:

  1. 瀏覽至 Azure 入口網站Navigate to the Azure portal.

  2. 找出您的儲存體帳戶。Locate your storage account.

  3. 在儲存體帳戶概觀的 [設定] 區段中,選取 [存取金鑰] 。In the Settings section of the storage account overview, select Access keys. 您的帳戶存取金鑰隨即出現,此外也會顯示每個金鑰的完整連接字串。Your account access keys appear, as well as the complete connection string for each key.

  4. 尋找 [金鑰1] 下方的 [連接字串] 值,然後按一下 [複製] 按鈕來複製連接字串。Find the Connection string value under key1, and click the Copy button to copy the connection string. 在下一個步驟中,您會將連接字串值新增至環境變數。You will add the connection string value to an environment variable in the next step.

    顯示如何從 Azure 入口網站複製連接字串的螢幕擷取畫面

解析連接字串Parse the connection string

適用於 .NET 的 Microsoft Azure Configuration Manager 程式庫 會提供一個類別,可用來剖析組態檔中的連接字串。The Microsoft Azure Configuration Manager Library for .NET provides a class for parsing a connection string from a configuration file. CloudConfigurationManager 類別可剖析組態設定,無論用戶端應用程式是在桌面、在行動裝置上、在 Azure 虛擬機器中,或在 Azure 雲端服務中執行。The CloudConfigurationManager class parses configuration settings regardless of whether the client application is running on the desktop, on a mobile device, in an Azure virtual machine, or in an Azure cloud service.

若要參考 CloudConfigurationManager 套件,請新增下列 using 指示詞︰To reference the CloudConfigurationManager package, add the following using directive:

using Microsoft.Azure; //Namespace for CloudConfigurationManager
using Microsoft.Azure.Storage;

以下範例示範如何從組態檔擷取連接字串:Here's an example that shows how to retrieve a connection string from a configuration file:

// Parse the connection string and return a reference to the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

是否使用 Azure Configuration Manager 可由您選擇。Using the Azure Configuration Manager is optional. 您也可以使用 API,例如 .NET Framework 的 ConfigurationManager 類別。You can also use an API like the .NET Framework's ConfigurationManager class.

建立佇列服務用戶端Create the Queue service client

CloudQueueClient 類別可讓您擷取佇列儲存體中儲存的佇列。The CloudQueueClient class enables you to retrieve queues stored in Queue storage. 以下是建立服務用戶端的其中一種方式:Here's one way to create the service client:

CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

您現在可以開始撰寫程式碼,以讀取佇列儲存體的資料並將資料寫入其中。Now you are ready to write code that reads data from and writes data to Queue storage.

建立佇列Create a queue

此範例說明如何建立尚不存在的佇列:This example shows how to create a queue if it does not already exist:

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a container.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

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

將訊息插入佇列Insert a message into a queue

若要將訊息插入現有佇列,請先建立新的 CloudQueueMessageTo insert a message into an existing queue, first create a new CloudQueueMessage. 接著,呼叫 AddMessage 方法。Next, call the AddMessage method. 您可以從字串 (採用 UTF-8 格式) 或位元組陣列建立 CloudQueueMessageA CloudQueueMessage can be created from either a string (in UTF-8 format) 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.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

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

// Create a message and add it to the queue.
CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.AddMessage(message);

查看下一個訊息Peek at the next message

透過呼叫 PeekMessage 方法,您可以在佇列前面查看訊息,而無需將它從佇列中移除。You can peek at the message in the front of a queue without removing it from the queue by calling the PeekMessage method.

// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Peek at the next message
CloudQueueMessage peekedMessage = queue.PeekMessage();

// Display message.
Console.WriteLine(peekedMessage.AsString);

變更佇列訊息的內容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.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Get the message from the queue and update the message contents.
CloudQueueMessage message = queue.GetMessage();
message.SetMessageContent2("Updated contents.", false);
queue.UpdateMessage(message,
    TimeSpan.FromSeconds(60.0),  // Make it invisible for another 60 seconds.
    MessageUpdateFields.Content | MessageUpdateFields.Visibility);

將下一個訊息清除佇列De-queue the next message

您的程式碼可以使用兩個步驟將訊息自佇列中清除佇列。Your code de-queues a message from a queue in two steps. 呼叫 GetMessage時,您會取得佇列中的下一個訊息。When you call GetMessage, you get the next message in a queue. GetMessage 傳回的訊息,對於從此佇列讀取訊息的任何其他程式碼而言將會是不可見的。A message returned from GetMessage becomes invisible to any other code reading messages from this queue. 依預設,此訊息會維持 30 秒的不可見狀態。By default, this message stays invisible for 30 seconds. 若要完成從佇列中移除訊息,您還必須呼叫 DeleteMessageTo finish removing the message from the queue, you must also call DeleteMessage. 這個移除訊息的兩步驟程序可確保您的程式碼因為硬體或軟體故障而無法處理訊息時,另一個程式碼的執行個體可以取得相同訊息並再試一次。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. 您的程式碼會在處理完訊息之後立即呼叫 DeleteMessageYour code calls DeleteMessage right after the message has been processed.

// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Get the next message
CloudQueueMessage retrievedMessage = queue.GetMessage();

//Process the message in less than 30 seconds, and then delete the message
queue.DeleteMessage(retrievedMessage);

搭配通用佇列儲存體 API 使用 Async-Await 模式Use Async-Await pattern with common Queue storage APIs

這個範例示範如何搭配通用佇列儲存體 API 使用 Async-Await 模式。This example shows how to use the Async-Await pattern with common Queue storage APIs. 此範例會呼叫每個指定方法的非同步版本,就像每個方法的非同步 Async 尾碼所指示的一樣。The sample calls the asynchronous version of each of the given methods, as indicated by the Async suffix of each method. 使用非同步方法時,async-await 模式會暫停本機執行,直到呼叫完成為止。When an async method is used, the async-await pattern suspends local execution until the call completes. 這種行為可讓目前的執行緒執行其他工作,有助於避免發生效能瓶頸並提升應用程式的整體回應。This behavior allows the current thread to do other work, which helps avoid performance bottlenecks and improves the overall responsiveness of your application. 如需在 .NET 中使用 Async-Await 模式的詳細資訊,請參閱 Async 和 Await (C# 和 Visual Basic)For more details on using the Async-Await pattern in .NET see Async and Await (C# and Visual Basic)

// Create the queue if it doesn't already exist
if(await queue.CreateIfNotExistsAsync())
{
    Console.WriteLine("Queue '{0}' Created", queue.Name);
}
else
{
    Console.WriteLine("Queue '{0}' Exists", queue.Name);
}

// Create a message to put in the queue
CloudQueueMessage cloudQueueMessage = new CloudQueueMessage("My message");

// Async enqueue the message
await queue.AddMessageAsync(cloudQueueMessage);
Console.WriteLine("Message added");

// Async dequeue the message
CloudQueueMessage retrievedMessage = await queue.GetMessageAsync();
Console.WriteLine("Retrieved message with content '{0}'", retrievedMessage.AsString);

// Async delete the message
await queue.DeleteMessageAsync(retrievedMessage);
Console.WriteLine("Deleted message");

運用清除佇列訊息的其他選項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. 下列程式碼範例將使用 GetMessages 方法,在一次呼叫中取得 20 個訊息。The following code example uses the GetMessages method to get 20 messages in one call. 接著它會使用 foreach 迴圈處理每個訊息。Then it processes each message using a foreach loop. 它也會將可見度逾時設定為每個訊息五分鐘。It also sets the invisibility timeout to five minutes for each message. 請注意,系統會針對所有訊息同時開始計時 5 分鐘,所以從呼叫 GetMessages開始的 5 分鐘後,任何尚未刪除的訊息都會重新出現。Note that the 5 minutes starts for all messages at the same time, so after 5 minutes have passed since the call to GetMessages, any messages which have not been deleted will become visible again.

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

foreach (CloudQueueMessage message in queue.GetMessages(20, TimeSpan.FromMinutes(5)))
{
    // Process all messages in less than 5 minutes, deleting each message after processing.
    queue.DeleteMessage(message);
}

取得佇列長度Get the queue length

您可以取得佇列中的估計訊息數目。You can get an estimate of the number of messages in a queue. FetchAttributes 方法會要求佇列服務擷取佇列屬性,其中包含訊息計數。The FetchAttributes method asks the Queue service to retrieve the queue attributes, including the message count. ApproximateMessageCount 屬性會傳回 FetchAttributes 方法所擷取的最後一個值,而無需呼叫佇列服務。The ApproximateMessageCount property returns the last value retrieved by the FetchAttributes method, without calling the Queue service.

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

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

// Retrieve the cached approximate message count.
int? cachedMessageCount = queue.ApproximateMessageCount;

// Display number of messages.
Console.WriteLine("Number of messages in queue: " + cachedMessageCount);

刪除佇列Delete a queue

若要刪除佇列及其內含的所有訊息,請在佇列物件上呼叫 Delete 方法。To delete a queue and all the messages contained in it, call the Delete method on the queue object.

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Delete the queue.
queue.Delete();

後續步驟Next steps

了解佇列儲存體的基礎概念之後,請參考下列連結以了解有關更複雜的儲存工作。Now that you've learned the basics of Queue storage, follow these links to learn about more complex storage tasks.