你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:适用于 .NET 的 Azure 队列存储客户端库

适用于 .NET 的 Azure 队列存储客户端库入门。 Azure 队列存储是一项可存储大量消息供以后检索和处理的服务。 请按照以下步骤安装程序包并试用基本任务的示例代码。

API 参考文档 | 库源代码 | 包 (NuGet) | 示例

使用适用于 .NET 的 Azure 队列存储客户端库完成以下操作:

  • 创建队列
  • 向队列添加消息
  • 查看队列中的消息
  • 更新队列中的消息
  • 获取队列长度
  • 从队列接收消息
  • 从队列中删除消息
  • 删除队列

先决条件

设置

本部分逐步指导你准备一个项目,使其与适用于 .NET 的 Azure 队列存储客户端库配合使用。

创建项目

创建名为 QueuesQuickstart 的 .NET 应用程序。

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 QueuesQuickstart 的新控制台应用。 此命令将创建一个简单的“hello world”C# 项目,其中包含名为 Program.cs 的单个源文件。

    dotnet new console -n QueuesQuickstart
    
  2. 切换到新创建的 QueuesQuickstart 目录。

    cd QueuesQuickstart
    

安装包

同样在应用程序目录中,使用 dotnet add package 命令安装适用于 .NET 包的 Azure 队列存储客户端库。

dotnet add package Azure.Storage.Queues

与 Azure 服务进行无密码连接时,还需要 Azure 标识客户端库包。

dotnet add package Azure.Identity

设置应用框架

  1. 在所选编辑器中打开项目
  2. 打开 Program.cs 文件
  3. 更新现有代码,使之与以下代码一致:
using Azure;
using Azure.Identity;
using Azure.Storage.Queues;
using Azure.Storage.Queues.Models;
using System;
using System.Threading.Tasks;

Console.WriteLine("Azure Queue Storage client library - .NET quickstart sample");

// Quickstart code goes here

向 Azure 进行身份验证

对大多数 Azure 服务的应用程序请求必须获得授权。 要在代码中实现与 Azure 服务的无密码连接,推荐使用 Azure 标识客户端库提供的 DefaultAzureCredential 类。

还可以直接使用密码、连接字符串或其他凭据授权对 Azure 服务的请求。 但是,应谨慎使用此方法。 开发人员必须尽量避免在不安全的位置公开这些机密。 任何可获得密码或密钥的人员都可进行身份验证。 DefaultAzureCredential 提供比帐户密钥更好的管理和安全优势,来实现无密码身份验证。 以下示例演示了这两个选项。

DefaultAzureCredential 是适用于 .NET 的 Azure 标识客户端库提供的类。 有关 DefaultAzureCredential 的详细信息,请参阅 DefaultAzureCredential 概述DefaultAzureCredential 支持多种身份验证方法,并确定应在运行时使用哪种方法。 通过这种方法,你的应用可在不同环境(本地与生产)中使用不同的身份验证方法,而无需实现特定于环境的代码。

例如,应用可在本地开发时使用 Visual Studio 登录凭据进行身份验证,然后在将其部署到 Azure 后使用托管标识。 此转换不需要进行任何代码更改。

在本地进行开发时,请确保访问队列数据的用户帐户具有正确的权限。 需有“存储队列数据参与者”角色才能读取和写入队列数据。 若要为你自己分配此角色,需要具有“用户访问管理员”角色,或者具有包含 Microsoft.Authorization/roleAssignments/write 操作的其他角色。 可使用 Azure 门户、Azure CLI 或 Azure PowerShell 向用户分配 Azure RBAC 角色。 可以在范围概述页上详细了解角色分配的可用范围。

在此方案中,你将为用户帐户分配权限(范围为存储帐户)以遵循最低权限原则。 这种做法仅为用户提供所需的最低权限,并创建更安全的生产环境。

以下示例将“存储队列数据参与者”角色分配给用户帐户,该角色提供对存储帐户中的队列数据的读取和写入访问权限。

重要

在大多数情况下,角色分配在 Azure 中传播需要一两分钟的时间,但极少数情况下最多可能需要 8 分钟。 如果在首次运行代码时收到身份验证错误,请稍等片刻再试。

  1. 在 Azure 门户中,使用主搜索栏或左侧导航找到存储帐户。

  2. 在存储帐户概述页的左侧菜单中选择“访问控制 (IAM)”。

  3. 在“访问控制 (IAM)”页上,选择“角色分配”选项卡。

  4. 从顶部菜单中选择“+ 添加”,然后从出现的下拉菜单中选择“添加角色分配”。

A screenshot showing how to assign a role.

  1. 使用搜索框将结果筛选为所需角色。 在此示例中,请搜索“存储队列数据参与者”并选择匹配的结果,然后选择“下一步”。

  2. 在“访问权限分配对象”下,选择“用户、组或服务主体”,然后选择“+ 选择成员”。

  3. 在对话框中,搜索 Microsoft Entra ID 用户名(通常是 user@domain 电子邮件地址),然后选中对话框底部的“选择”。

  4. 选择“查看 + 分配”转到最后一页,然后再次选择“查看 + 分配”完成该过程。

对象模型

Azure 队列存储是一项可存储大量消息的服务。 队列消息大小最大可为 64 KB。 一个队列可以包含数百万条消息,直至达到存储帐户的总容量限值。 队列通常用于创建要异步处理的积压工作 (backlog)。 队列存储提供了三种类型的资源:

  • 存储帐户:对 Azure 存储的所有访问都要通过存储帐户来完成。 有关存储帐户的详细信息,请参阅存储帐户概述
  • 队列:一个队列包含一组消息。 所有消息必须位于相应的队列中。 请注意,队列名称必须全部小写。 有关命名队列的信息,请参阅 命名队列和元数据
  • 消息:一条消息(无论哪种格式)的最大大小为 64 KB。 消息最多可以在队列中保留 7 天。 在 2017-07-29 或更高版本中,最大生存时间可以是任何正数,或者是 -1(表示消息不会过期)。 如果省略此参数,则默认的生存时间为 7 天。

以下图示显示了这些资源之间的关系。

Diagram of Queue storage architecture

使用以下 .NET 类与这些资源进行交互:

代码示例

这些示例代码片段演示如何使用适用于 .NET 的 Azure 队列存储客户端库执行以下操作:

授予访问权限并创建客户端对象

对于本地开发,请确保使用分配了该角色的同一 Microsoft Entra 帐户进行身份验证。 可以通过常用的开发工具(如 Azure CLI 或 Azure PowerShell)进行身份验证。 可用于进行身份验证的开发工具因语言而异。

使用以下命令通过 Azure CLI 登录到 Azure:

az login

进行身份验证后,可以使用 DefaultAzureCredential 创建和授权 QueueClient 对象,以便访问存储帐户中的队列数据。 DefaultAzureCredential 将自动发现并使用你在上一步用来登录的帐户。

若要使用 DefaultAzureCredential 进行授权,请确保已添加 Azure.Identity 包,如安装包中所述。 此外,请确保在 Program.cs 文件中为 Azure.Identity 命名空间添加 using 指令:

using Azure.Identity;

接下来,请确定队列的名称并创建 QueueClient 类的实例,使用 DefaultAzureCredential 进行授权。 我们使用此客户端对象创建存储帐户中的队列资源并与之交互。

重要

队列名称只能包含小写字母、数字和连字符,并且必须以字母或数字开头。 每个连字符的前后必须为非连字符字符。 名称的长度还必须介于 3 到 63 个字符之间。 有关详细信息,请参阅命名队列和元数据

将以下代码添加到 Program.cs 文件尾部。 请务必替换 <storage-account-name> 占位符值:

// Create a unique name for the queue
// TODO: Replace the <storage-account-name> placeholder 
string queueName = "quickstartqueues-" + Guid.NewGuid().ToString();
string storageAccountName = "<storage-account-name>";

// Instantiate a QueueClient to create and interact with the queue
QueueClient queueClient = new QueueClient(
    new Uri($"https://{storageAccountName}.queue.core.windows.net/{queueName}"),
    new DefaultAzureCredential());

注意

使用 QueueClient 类发送的消息必须采用可包含在具有 UTF-8 编码的 XML 请求中的格式。 或者,可以将 MessageEncoding 选项设置为 Base64 来处理不符合规范的消息。

创建队列

使用 QueueClient 对象,通过调用 CreateAsync 方法在存储帐户中创建队列。

将以下代码添加到 Program.cs 方法尾部:

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

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

向队列添加消息

以下代码片段通过调用 SendMessageAsync 方法,以异步方式将消息添加到队列。 它还保存从 SendMessageAsync 调用返回的 SendReceipt。 收据用于在稍后的程序中更新消息。

将以下代码添加到 Program.cs 文件尾部:

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");

查看队列中的消息

通过调用 PeekMessagesAsync 方法,查看队列中的消息。 此方法从队列前面检索一条或多条消息,但不更改消息的可见性。

将以下代码添加到 Program.cs 文件尾部:

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}");
}

更新队列中的消息

通过调用 UpdateMessageAsync 方法来更新消息的内容。 此方法可以更改消息的可见性超时和内容。 消息内容必须是最大为 64 KB 的 UTF-8 编码字符串。 除了该消息的新内容,还会传入代码中之前保存的 SendReceipt 中的值。 SendReceipt 值标识要更新的消息。

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");

获取队列长度

可以获取队列中消息的估计数。 GetProperties 方法返回包括消息计数在内的队列属性。 ApproximateMessagesCount 属性包含队列中的大致消息数。 该数字不低于队列中的实际消息数,但可能高于实际消息数。

将以下代码添加到 Program.cs 文件尾部:

QueueProperties properties = queueClient.GetProperties();

// Retrieve the cached approximate message count
int cachedMessagesCount = properties.ApproximateMessagesCount;

// Display number of messages
Console.WriteLine($"Number of messages in queue: {cachedMessagesCount}");

从队列接收消息

通过调用 ReceiveMessagesAsync 方法,下载以前添加的消息。

将以下代码添加到 Program.cs 文件尾部:

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

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

可以选择为 maxMessages 指定一个值,该值是要从队列中检索的消息数。 默认值为 1 条消息,最大值为 32 条消息。 还可以为 visibilityTimeout 指定一个值,该值代表在超时期间对其他操作隐藏的消息数。 默认为 30 秒。

从队列中删除消息

在处理完消息后,将消息从队列中删除。 在本例中,“处理”即在控制台上显示消息。

在处理和删除消息之前,应用会调用 Console.ReadLine 以暂停并等待用户输入。 在删除资源之前,请先在 Azure 门户中验证资源已正确创建。 任何未显式删除的消息最终会再次显示在队列中,以便处理它们。

将以下代码添加到 Program.cs 文件尾部:

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);
}

删除队列

以下代码使用 DeleteAsync 方法来删除队列,以便清除该应用所创建的资源。

将以下代码添加到 Program.cs 文件尾部:

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");

运行代码

此应用创建三条消息并将其添加到 Azure 队列。 此代码列出队列中的消息,然后检索并删除它们,最后删除队列。

在控制台窗口中,导航到应用程序目录,然后生成并运行应用程序。

dotnet build
dotnet run

应用的输出类似于以下示例:

Azure Queue Storage client library - .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 门户中检查存储帐户。 验证消息是否在队列中。

Enter 接收和删除消息。 出现提示时,请再次按 Enter,删除队列并完成演示。

后续步骤

在本快速入门中,你学习了如何使用异步 .NET 代码创建队列并向其添加消息。 然后,你了解如何查看、检索和删除消息。 最后,你还了解了如何删除消息队列。

有关教程、示例、快速入门和其他文档,请访问: