快速入门:适用于 .NET 的 Azure 队列存储客户端库 v12Quickstart: Azure Queue storage client library v12 for .NET

适用于 .NET 的 Azure 队列存储客户端库 v12 入门。Get started with the Azure Queue storage client library version 12 for .NET. Azure 队列存储是一项可存储大量消息供以后检索和处理的服务。Azure Queue storage is a service for storing large numbers of messages for later retrieval and processing. 请按照以下步骤安装包并试用基本任务的示例代码。Follow these steps to install the package and try out example code for basic tasks.

使用适用于 .NET 的 Azure 队列存储客户端库 v12 完成以下操作:Use the Azure Queue storage client library v12 for .NET to:

  • 创建队列Create a queue
  • 向队列添加消息Add messages to a queue
  • 查看队列中的消息Peek at messages in a queue
  • 更新队列中的消息Update a message in a queue
  • 从队列接收消息Receive messages from a queue
  • 从队列中删除消息Delete messages from a queue
  • 删除队列Delete a queue

其他资源:Additional resources:

先决条件Prerequisites

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 .NET 的 Azure 队列存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Queue storage client library v12 for .NET.

创建项目Create the project

创建名为 QueuesQuickstartV12 的 .NET Core 应用程序。Create a .NET Core application named QueuesQuickstartV12.

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 QueuesQuickstartV12 的新控制台应用。In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name QueuesQuickstartV12. 此命令将创建包含单个源文件的简单“Hello World”C# 项目:Program.csThis command creates a simple "Hello World" C# project with a single source file: Program.cs.

    dotnet new console -n QueuesQuickstartV12
    
  2. 切换到新创建的 QueuesQuickstartV12 目录。Switch to the newly created QueuesQuickstartV12 directory.

    cd QueuesQuickstartV12
    

安装包Install the package

仍在应用程序目录中时,使用 dotnet add package 命令安装适用于 .NET 包的 Azure 队列存储客户端库。While still in the application directory, install the Azure Queue storage client library for .NET package by using the dotnet add package command.

dotnet add package Azure.Storage.Queues

设置应用框架Set up the app framework

从项目目录中执行以下操作:From the project directory:

  1. 在编辑器中打开 Program.cs 文件Open the Program.cs file in your editor
  2. 删除 Console.WriteLine("Hello World!"); 语句Remove the Console.WriteLine("Hello World!"); statement
  3. 添加 using 指令Add using directives
  4. 更新 Main 方法声明以支持异步代码Update the Main method declaration to support async code

代码如下:Here's the code:

using Azure;
using Azure.Storage.Queues;
using Azure.Storage.Queues.Models;
using System;
using System.Threading.Tasks;

namespace QueuesQuickstartV12
{
    class Program
    {
        static async Task Main(string[] args)
        {
        }
    }
}

从 Azure 门户复制凭据Copy your credentials from the Azure portal

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 找到自己的存储帐户。Locate your storage account.

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

  4. 找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。 Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

配置存储连接字符串Configure your storage connection string

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your connection string, write it to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并遵照适用于操作系统的说明。To set the environment variable, open a console window, and follow the instructions for your operating system. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

WindowsWindows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.

LinuxLinux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOSmacOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure 队列存储是一个可存储大量消息的服务。Azure Queue storage is a service for storing large numbers of messages. 队列消息大小最大可为 64 KB。A queue message can be up to 64 KB in size. 一个队列可以包含数百万条消息,直至达到存储帐户的总容量限值。A queue may contain millions of messages, up to the total capacity limit of a storage account. 队列通常用于创建要异步处理的积压工作 (backlog)。Queues are commonly used to create a backlog of work to process asynchronously. 队列存储提供三种类型的资源:Queue storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的队列A queue in the storage account
  • 队列中的消息Messages within the queue

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

队列存储体系结构的图示

使用以下 .NET 类与这些资源进行交互:Use the following .NET classes to interact with these resources:

  • QueueServiceClient:通过 QueueServiceClient 可管理存储帐户中的所有队列。QueueServiceClient: The QueueServiceClient allows you to manage the all queues in your storage account.
  • QueueClient:通过 QueueClient 类可管理和操纵单个队列及其消息。QueueClient: The QueueClient class allows you to manage and manipulate an individual queue and its messages.
  • QueueMessageQueueMessage 类表示在队列上调用 ReceiveMessages 时返回的单个对象。QueueMessage: The QueueMessage class represents the individual objects returned when calling ReceiveMessages on a queue.

代码示例Code examples

这些示例代码片段演示如何使用适用于 .NET 的 Azure 队列存储客户端库执行以下操作:These example code snippets show you how to do the following actions with the Azure Queue storage client library for .NET:

获取连接字符串Get the connection string

以下代码检索存储帐户的连接字符串。The code below retrieves the connection string for the storage account. 连接字符串存储在配置存储连接字符串部分创建的环境变量中。The connection string is stored in the environment variable created in the Configure your storage connection string section.

Main 方法内添加此代码:Add this code inside the Main method:

Console.WriteLine("Azure Queue storage v12 - .NET quickstart sample\n");

// Retrieve the connection string for use with the application. The storage
// connection string is stored in an environment variable called
// AZURE_STORAGE_CONNECTION_STRING on the machine running the application.
// If the environment variable is created after the application is launched
// in a console or with Visual Studio, the shell or application needs to be
// closed and reloaded to take the environment variable into account.
string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

创建队列Create a queue

确定新队列的名称。Decide on a name for the new queue. 以下代码将 GUID 值追加到队列名称,从而确保其是唯一的。The code below appends a GUID value to the queue name to ensure that it's unique.

重要

队列名称只能包含小写字母、数字和连字符,并且必须以字母或数字开头。Queue names may only contain lowercase letters, numbers, and hyphens, and must begin with a letter or a number. 每个连字符的前后必须为非连字符字符。Each hyphen must be preceded and followed by a non-hyphen character. 名称的长度还必须介于 3 到 63 个字符之间。The name must also be between 3 and 63 characters long. 有关命名队列的详细信息,请参阅命名队列和元数据For more information about naming queues, see Naming Queues and Metadata.

创建 QueueClient 类的实例。Create an instance of the QueueClient class. 然后,调用 CreateAsync 方法在存储帐户中创建队列。Then, call the CreateAsync method to create the queue in your storage account.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// Create a unique name for the queue
string queueName = "quickstartqueues-" + Guid.NewGuid().ToString();

Console.WriteLine($"Creating queue: {queueName}");

// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClient(connectionString, queueName);

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

向队列添加消息Add messages to a queue

以下代码片段通过调用 SendMessageAsync 方法,以异步方式将消息添加到队列。The following code snippet asynchronously adds messages to queue by calling the SendMessageAsync method. 它还保存从 SendMessageAsync 调用返回的 SendReceiptIt also saves a SendReceipt returned from a SendMessageAsync call. 收据用于在稍后的程序中更新消息。The receipt is used to update the message later in the program.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

Console.WriteLine("\nAdding messages to the queue...");

// Send several messages to the queue
await queueClient.SendMessageAsync("First message");
await queueClient.SendMessageAsync("Second message");

// Save the receipt so we can update this message later
SendReceipt receipt = await queueClient.SendMessageAsync("Third message");

查看队列中的消息Peek at messages in a queue

通过调用 PeekMessagesAsync 方法,查看队列中的消息。Peek at the messages in the queue by calling the PeekMessagesAsync method. PeekMessagesAsync 方法从队列的前部检索一条或多条消息,但不会更改消息的可见性。The PeekMessagesAsync method retrieves one or more messages from the front of the queue but doesn't alter the visibility of the message.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

Console.WriteLine("\nPeek at the messages in the queue...");

// Peek at messages in the queue
PeekedMessage[] peekedMessages = await queueClient.PeekMessagesAsync(maxMessages: 10);

foreach (PeekedMessage peekedMessage in peekedMessages)
{
    // Display the message
    Console.WriteLine($"Message: {peekedMessage.MessageText}");
}

更新队列中的消息Update a message in a queue

通过调用 UpdateMessageAsync 方法来更新消息的内容。Update the contents of a message by calling the UpdateMessageAsync method. UpdateMessageAsync 方法可以更改消息的可见性超时和内容。The UpdateMessageAsync method can change a message's visibility timeout and contents. 消息内容必须是最大为 64 KB 的 UTF-8 编码字符串。The message content must be a UTF-8 encoded string that is up to 64 KB in size. 除了该消息的新内容,还会传入代码中之前保存的 SendReceipt 中的值。Along with the new content for the message, pass in the values from the SendReceipt that was saved earlier in the code. SendReceipt 值标识要更新的消息。The SendReceipt values identify which message to update.

Console.WriteLine("\nUpdating the third message in the queue...");

// Update a message using the saved receipt from sending the message
await queueClient.UpdateMessageAsync(receipt.MessageId, receipt.PopReceipt, "Third message has been updated");

从队列接收消息Receive messages from a queue

通过调用 ReceiveMessagesAsync 方法,下载以前添加的消息。Download previously added messages by calling the ReceiveMessagesAsync method.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

Console.WriteLine("\nReceiving messages from the queue...");

// Get messages from the queue
QueueMessage[] messages = await queueClient.ReceiveMessagesAsync(maxMessages: 10);

删除队列中的消息Delete messages from a queue

在处理完消息后,将消息从队列中删除。Delete messages from the queue after they're been processed. 在这种情况下,处理只是在控制台上显示消息。In this case, processing is just displaying the message on the console.

在处理和删除消息之前,应用会调用 Console.ReadLine 以暂停并等待用户输入。The app pauses for user input by calling Console.ReadLine before it processes and deletes the messages. 在删除资源之前,请先在 Azure 门户中验证资源已正确创建。Verify in your Azure portal that the resources were created correctly, before they're deleted. 未显式删除的任何消息都将在队列中再次变为可见,以方便再一次进行处理。Any messages not explicitly deleted will eventually become visible in the queue again for another chance to process them.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

Console.WriteLine("\nPress Enter key to 'process' messages and delete them from the queue...");
Console.ReadLine();

// Process and delete messages from the queue
foreach (QueueMessage message in messages)
{
    // "Process" the message
    Console.WriteLine($"Message: {message.MessageText}");

    // Let the service know we're finished with
    // the message and it can be safely deleted.
    await queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);
}

删除队列Delete a queue

以下代码使用 DeleteAsync 方法来删除队列,以便清除该应用所创建的资源。The following code cleans up the resources the app created by deleting the queue using the DeleteAsync method.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

Console.WriteLine("\nPress Enter key to delete the queue...");
Console.ReadLine();

// Clean up
Console.WriteLine($"Deleting queue: {queueClient.Name}");
await queueClient.DeleteAsync();

Console.WriteLine("Done");

运行代码Run the code

此应用创建三条消息并将其添加到 Azure 队列。This app creates and adds three messages to an Azure queue. 此代码列出队列中的消息,然后检索并删除它们,最后删除队列。The code lists the messages in the queue, then retrieves and deletes them, before finally deleting the queue.

在控制台窗口中,导航到应用程序目录,然后生成并运行应用程序。In your console window, navigate to your application directory, then build and run the application.

dotnet build
dotnet run

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Queue storage v12 - .NET quickstart sample

Creating queue: quickstartqueues-5c72da2c-30cc-4f09-b05c-a95d9da52af2

Adding messages to the queue...

Peek at the messages in the queue...
Message: First message
Message: Second message
Message: Third message

Updating the third message in the queue...

Receiving messages from the queue...

Press Enter key to 'process' messages and delete them from the queue...

Message: First message
Message: Second message
Message: Third message has been updated

Press Enter key to delete the queue...

Deleting queue: quickstartqueues-5c72da2c-30cc-4f09-b05c-a95d9da52af2
Done

当应用在接收到消息之前暂停时,请在 Azure 门户中检查存储帐户。When the app pauses before receiving messages, check your storage account in the Azure portal. 验证消息是否在队列中。Verify the messages are in the queue.

按“Enter”键接收和删除消息。Press the Enter key to receive and delete the messages. 出现提示时,请再次按“Enter”键,删除队列并完成演示。When prompted, press the Enter key again to delete the queue and finish the demo.

后续步骤Next steps

在本快速入门中,你学习了如何使用异步 .NET 代码创建队列并向其添加消息。In this quickstart, you learned how to create a queue and add messages to it using asynchronous .NET code. 然后,你了解如何查看、检索和删除消息。Then you learned to peek, retrieve, and delete messages. 最后,你还了解了如何删除消息队列。Finally, you learned how to delete a message queue.

有关教程、示例、快速入门和其他文档,请访问:For tutorials, samples, quick starts and other documentation, visit: