快速入门:使用适用于 .NET 的 Azure 存储 SDK v11 管理队列Quickstart: Use the Azure Storage SDK v11 for .NET to manage a queue

本快速入门介绍如何使用适用于 .NET 的 Azure 存储客户端库(版本 11)创建队列并在其中添加消息。In this quickstart, you learn how to use the Azure Storage client library version 11 for .NET to create a queue and add messages to it. 接下来,介绍如何在队列中读取和处理消息。Next, you learn how to read and process messages from the queue.

先决条件Prerequisites

若要访问 Azure 存储,需要一个 Azure 订阅。To access Azure Storage, you'll need an Azure subscription. 如果还没有订阅,请在开始前创建一个 1 元试用帐户If you don't already have a subscription, create a 1rmb trial account before you begin.

对 Azure 存储进行的所有访问都要通过存储帐户完成。All access to Azure Storage takes place through a storage account. 对于本快速入门,请使用 Azure 门户、Azure PowerShell 或 Azure CLI 创建存储帐户。For this quickstart, create a storage account using the Azure portal, Azure PowerShell, or Azure CLI. 有关如何创建帐户的帮助,请参阅创建存储帐户For help creating the account, see Create a storage account.

接下来,请下载并安装适用于操作系统的 .NET Core 2.0。Next, download and install .NET Core 2.0 for your operating system. 如果运行的是 Windows,可以安装 Visual Studio 并根据偏好使用 .NET Framework。If you are running Windows, you can install Visual Studio and use the .NET Framework if you prefer. 也可选择安装一个可以在操作系统中使用的编辑器。You can also choose to install an editor to use with your operating system.

WindowsWindows

有关在 .NET Core 与 .NET Framework 之间做出选择的信息,请参阅为服务器应用选择 .NET Core 或 .NET FrameworkFor information about choosing between .NET Core and the .NET Framework, see Choose between .NET Core and .NET Framework for server apps.

LinuxLinux

macOSmacOS

下载示例应用程序Download the sample application

本快速入门中使用的示例应用程序是基本的控制台应用程序。The sample application used in this quickstart is a basic console application. 可以浏览 GitHub 上的示例应用程序。You can explore the sample application on GitHub.

使用 git 可将应用程序的副本下载到开发环境。Use git to download a copy of the application to your development environment.

git clone https://github.com/Azure-Samples/storage-queues-dotnet-quickstart.git

此命令会将存储库克隆到本地 git 文件夹。This command clones the repository to your local git folder. 若要打开 Visual Studio 解决方案,请找到 storage-queues-dotnet-quickstart 文件夹并将其打开,然后双击“storage-queues-dotnet-quickstart.sln”。 To open the Visual Studio solution, look for the storage-queues-dotnet-quickstart folder, open it, and double-click on storage-queues-dotnet-quickstart.sln.

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

此示例应用程序需对存储帐户访问进行身份验证。The sample application needs to authenticate access to your storage account. 若要进行身份验证,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authenticate, 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

若要运行应用程序,必须为存储帐户提供连接字符串。To run the application, you must provide the connection string for your storage account. 此示例应用程序从环境变量中读取连接字符串,并使用它对 Azure 存储请求进行授权。The sample application reads the connection string from an environment variable and uses it to authorize requests to Azure Storage.

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。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 storageconnectionstring "<yourconnectionstring>"

添加环境变量后,可能需要重启任何正在运行的、需要读取环境变量的程序(包括控制台窗口)。After you add the environment variable, you may need to restart any running programs that will need to read the environment variable, including the console window. 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。For example, if you are using Visual Studio as your editor, restart Visual Studio before running the sample.

LinuxLinux

export storageconnectionstring=<yourconnectionstring>

添加环境变量后,请从控制台窗口运行 source ~/.bashrc,使更改生效。After you add the environment variable, run source ~/.bashrc from your console window to make the changes effective.

macOSmacOS

编辑 .bash_profile,然后添加环境变量:Edit your .bash_profile, and add the environment variable:

export STORAGE_CONNECTION_STRING=<yourconnectionstring>

添加环境变量后,请从控制台窗口运行 source .bash_profile,使更改生效。After you add the environment variable, run source .bash_profile from your console window to make the changes effective.

运行示例Run the sample

该示例应用程序创建一个队列并在其中添加消息。The sample application creates a queue and adds a message to it. 该应用程序首先扫视消息但不会将其从队列中删除,然后检索该消息并将其从队列中删除。The application first peeks at the message without removing it from the queue, then retrieves the message and deletes it from the queue.

WindowsWindows

如果使用 Visual Studio 作为编辑器,可以按 F5 运行应用程序。If you are using Visual Studio as your editor, you can press F5 to run.

否则,请导航到应用程序目录,并使用 dotnet run 命令运行应用程序。Otherwise, navigate to your application directory and run the application with the dotnet run command.

dotnet run

LinuxLinux

导航到你的应用程序目录并使用 dotnet run 命令运行应用程序。Navigate to your application directory and run the application with the dotnet run command.

dotnet run

macOSmacOS

导航到你的应用程序目录并使用 dotnet run 命令运行应用程序。Navigate to your application directory and run the application with the dotnet run command.

dotnet run

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

Azure Queues - .NET Quickstart sample

Created queue 'quickstartqueues-3136fe9a-fa52-4b19-a447-8999a847da52'

Added message 'aa8fa95f-07ea-4df7-bf86-82b3f7debfb7' to queue 'quickstartqueues-3136fe9a-fa52-4b19-a447-8999a847da52'
Message insertion time: 2/7/2019 4:30:46 AM +00:00
Message expiration time: 2/14/2019 4:30:46 AM +00:00

Contents of peeked message 'aa8fa95f-07ea-4df7-bf86-82b3f7debfb7': Hello, World

Message 'aa8fa95f-07ea-4df7-bf86-82b3f7debfb7' becomes visible again at 2/7/2019 4:31:16 AM +00:00

Processed and deleted message 'aa8fa95f-07ea-4df7-bf86-82b3f7debfb7'

Press any key to delete the sample queue.

了解示例代码Understand the sample code

接下来介绍示例代码,探讨其工作方式。Next, explore the sample code so that you can understand how it works.

尝试分析连接字符串Try parsing the connection string

该示例首先检查环境变量是否包含一个连接字符串,该字符串在经过分析后可以创建一个指向存储帐户的 CloudStorageAccount 对象。The sample first checks that the environment variable contains a connection string that can be parsed to create a CloudStorageAccount object pointing to the storage account. 该示例使用 TryParse 方法检查连接字符串是否有效。To check that the connection string is valid, the sample uses the TryParse method. 如果 TryParse 成功,它会初始化 storageAccount 变量并返回 trueIf TryParse is successful, it initializes the storageAccount variable and returns true.

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

// Check whether the connection string can be parsed.
if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
{
    // If the connection string is valid, proceed with calls to Azure Queues here.
    ...    
}
else
{
    Console.WriteLine(
        "A connection string has not been defined in the system environment variables. " +
        "Add an environment variable named 'storageconnectionstring' with your storage " +
        "connection string as a value.");
}

创建队列Create the queue

首先,该示例创建一个队列并在其中添加消息。First, the sample creates a queue and adds a message to it.

// Create a queue called 'quickstartqueues' and append a GUID value so that the queue name 
// is unique in your storage account. 
queue = cloudQueueClient.GetQueueReference("quickstartqueues-" + Guid.NewGuid().ToString());
await queue.CreateAsync();

Console.WriteLine("Created queue '{0}'", queue.Name);
Console.WriteLine();

添加消息Add a message

接下来,该示例将消息添加到队列的后部。Next, the sample adds a message to the back of the queue.

消息必须采用可包含在 XML 请求中的 UTF-8 编码格式,大小不能超过 64 KB。A message must be in a format that can be included in an XML request with UTF-8 encoding, and may be up to 64 KB in size. 如果消息包含二进制数据,则我们建议对消息进行 Base64 编码。If a message contains binary data, we recommend that you Base64-encode the message.

消息的最大生存时间默认设置为 7 天。By default, the maximum time-to-live for a message is set to 7 days. 可以为消息生存时间指定任何正数。You can specify any positive number for the message time-to-live.

// Create a message and add it to the queue. Set expiration time to 14 days.
CloudQueueMessage message = new CloudQueueMessage("Hello, World");
await queue.AddMessageAsync(message, new TimeSpan(14,0,0,0), null, null, null);
Console.WriteLine("Added message '{0}' to queue '{1}'", message.Id, queue.Name);
Console.WriteLine("Message insertion time: {0}", message.InsertionTime.ToString());
Console.WriteLine("Message expiration time: {0}", message.ExpirationTime.ToString());
Console.WriteLine();

若要添加未过期的消息,请在对 AddMessageAsync 的调用中使用 Timespan.FromSeconds(-1)To add a message that does not expire, use Timespan.FromSeconds(-1) in your call to AddMessageAsync.

await queue.AddMessageAsync(message, TimeSpan.FromSeconds(-1), null, null, null);

扫视队列中的消息Peek a message from the queue

该示例演示如何扫视队列中的消息。The sample shows how to peek a message from a queue. 扫视消息时,可以读取该消息的内容。When you peek a message, you can read the contents of the message. 但是,该消息仍对其他客户端可见,使其他客户端随后可以检索并处理该消息。However, the message remains visible to other clients, so that another client can subsequently retrieve and process the message.

// Peek at the message at the front of the queue. Peeking does not alter the message's 
// visibility, so that another client can still retrieve and process it. 
CloudQueueMessage peekedMessage = await queue.PeekMessageAsync();

// Display the ID and contents of the peeked message.
Console.WriteLine("Contents of peeked message '{0}': {1}", peekedMessage.Id, peekedMessage.AsString);
Console.WriteLine();

取消消息排队Dequeue a message

该示例还演示了如何取消消息的排队。The sample also shows how to dequeue a message. 取消消息的排队时,会从队列的前部检索该消息,并使该消息暂时对其他客户端不可见。When you dequeue a message, you retrieve the message from the front of the queue and render it temporarily invisible to other clients. 默认情况下,消息将持续 30 秒不可见。By default, a message remains invisible for 30 seconds. 在此期间,代码可以处理该消息。During this time, your code can process the message. 若要完成取消消息排队,请在处理后立即删除该消息,使其他客户端不会将同一条消息取消排队。To finish dequeueing the message, you delete the message immediately after processing, so that another client does not dequeue the same message.

如果代码由于硬件或软件故障而无法处理消息,则不可见持续时间过后,该消息将再次可见。If your code fails to process a message due to a hardware or software failure, then the message becomes visible again after the period of invisibility has lapsed. 其他客户端可以检索同一消息并重试。Another client can retrieve the same message and try again.

// Retrieve the message at the front of the queue. The message becomes invisible for 
// a specified interval, during which the client attempts to process it.
CloudQueueMessage retrievedMessage = await queue.GetMessageAsync();

// Display the time at which the message will become visible again if it is not deleted.
Console.WriteLine("Message '{0}' becomes visible again at {1}", retrievedMessage.Id, retrievedMessage.NextVisibleTime);
Console.WriteLine();

//Process and delete the message within the period of invisibility.
await queue.DeleteMessageAsync(retrievedMessage);
Console.WriteLine("Processed and deleted message '{0}'", retrievedMessage.Id);
Console.WriteLine();

清理资源Clean up resources

该示例通过删除队列来清理它所创建的资源。The sample cleans up the resources that it created by deleting the queue. 删除队列也会删除该队列中包含的所有消息。Deleting the queue also deletes any messages it contains.

Console.WriteLine("Press any key to delete the sample queue.");
Console.ReadLine();
Console.WriteLine("Deleting the queue and any messages it contains...");
Console.WriteLine();
if (queue != null)
{
    await queue.DeleteIfExistsAsync();
}

用于开发包含队列的 .NET 应用程序的资源Resources for developing .NET applications with queues

请参阅以下附加资源,了解如何开发包含 Azure 队列的 .NET 应用程序:See these additional resources for .NET development with Azure Queues:

二进制文件和源代码Binaries and source code

客户端库参考和示例Client library reference and samples

后续步骤Next steps

本快速入门介绍了如何将消息添加到队列、扫视队列中的消息、取消消息排队,以及使用 .NET 处理消息。In this quickstart, you learned how to add messages to a queue, peek messages from a queue, and dequeue and process messages using .NET.