如何通过 Ruby 使用队列存储How to use Queue storage from Ruby

提示

尝试 Azure 存储资源管理器Try the Azure Storage Explorer

Azure 存储资源管理器是 Microsoft 免费提供的独立应用,适用于在 Windows、macOS 和 Linux 上以可视方式处理 Azure 存储数据。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 shows you how to perform common scenarios using the Azure Queue Storage service. 相关示例是使用 Ruby Azure API 编写的。The samples are written using the Ruby Azure API. 介绍的方案包括插入扫视获取删除队列消息以及创建和删除队列The scenarios covered include inserting, peeking, getting, and deleting queue messages, as well as creating and deleting queues.

什么是队列存储?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.chinacloudapi.cn/<queue>URL format: Queues are addressable using the following URL format: http://<storage account>.queue.core.chinacloudapi.cn/<queue>

    可使用以下 URL 访问示意图中的某个队列:The following URL addresses a queue in the diagram:

    http://myaccount.queue.core.chinacloudapi.cn/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适用于 .NET 的 Azure 存储资源提供程序创建 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.

创建 Ruby 应用程序Create a Ruby Application

创建 Ruby 应用程序。Create a Ruby application.

配置应用程序以访问存储Configure Your Application to Access Storage

要使用 Azure 存储,需要下载和使用 Ruby azure 包,其中包括一组便于与存储 REST 服务进行通信的库。To use Azure storage, you need to download and use the Ruby azure package, which includes a set of convenience libraries that communicate with the storage REST services.

使用 RubyGems 获取该程序包Use RubyGems to obtain the package

  1. 使用命令行接口,例如 PowerShell (Windows)、Terminal (Mac) 或 Bash (Unix)。Use a command-line interface such as PowerShell (Windows), Terminal (Mac), or Bash (Unix).
  2. 在命令窗口中键入“gem install azure”以安装 gem 和依赖项。Type "gem install azure" in the command window to install the gem and dependencies.

导入包Import the package

使用常用的文本编辑器将以下内容添加到要在其中使用存储的 Ruby 文件的顶部:Use your favorite text editor, add the following to the top of the Ruby file where you intend to use storage:

require "azure"

设置 Azure 存储连接Setup an Azure Storage Connection

Azure 模块会读取环境变量 AZURE_STORAGE_ACCOUNTAZURE_STORAGE_ACCESS_KEY 以获取连接到 Azure 存储帐户所需的信息。The azure module will read the environment variables AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY for information required to connect to your Azure storage account. 如果未设置这些环境变量,则在使用 Azure::QueueService 前必须通过以下代码指定帐户信息:If these environment variables are not set, you must specify the account information before using Azure::QueueService with the following code:

Azure.config.storage_account_name = "<your azure storage account>"
Azure.config.storage_access_key = "<your Azure storage access key>"

从 Azure 门户中的经典或 Resource Manager 存储帐户中获取这些值:To obtain these values from a classic or Resource Manager storage account in the Azure portal:

  1. 登录到 Azure 门户Log in to the Azure portal.
  2. 导航到要使用的存储帐户。Navigate to the storage account you want to use.
  3. 在右侧的“设置”边栏选项卡中,单击“访问密钥” 。In the Settings blade on the right, click Access Keys.
  4. 在出现的“访问密钥”边栏选项卡中,将看到访问密钥 1 和访问密钥 2。In the Access keys blade that appears, you'll see the access key 1 and access key 2. 可以使用其中任意一个。You can use either of these.
  5. 单击复制图标以将键复制到剪贴板。Click the copy icon to copy the key to the clipboard.

如何:创建队列How To: Create a Queue

以下代码将创建一个 Azure::QueueService 对象,用于处理队列。The following code creates a Azure::QueueService object, which enables you to work with queues.

azure_queue_service = Azure::QueueService.new

使用 create_queue() 方法创建具有指定名称的队列。Use the create_queue() method to create a queue with the specified name.

begin
  azure_queue_service.create_queue("test-queue")
rescue
  puts $!
end

如何:在队列中插入消息How To: Insert a Message into a Queue

要在队列中插入消息,可使用 create_message() 方法创建一条新消息并将其添加到队列中。To insert a message into a queue, use the create_message() method to create a new message and add it to the queue.

azure_queue_service.create_message("test-queue", "test message")

如何:扫视下一条消息How To: Peek at the Next Message

可调用 peek_messages() 方法,查看队列前面的消息,而不必从队列中将其删除。You can peek at the message in the front of a queue without removing it from the queue by calling the peek_messages() method. 默认情况下,peek_messages() 扫视单条消息。By default, peek_messages() peeks at a single message. 也可以指定要扫视的消息数。You can also specify how many messages you want to peek.

result = azure_queue_service.peek_messages("test-queue",
  {:number_of_messages => 10})

如何:取消对下一条消息的排队How To: Dequeue the Next Message

可通过两个步骤从队列中删除消息。You can remove a message from a queue in two steps.

  1. 在调用 list_messages() 时,默认情况下会获取队列中的下一条消息。When you call list_messages(), you get the next message in a queue by default. 也可以指定要获取的消息数。You can also specify how many messages you want to get. list_messages() 返回的消息变得对从此队列读取消息的任何其他代码不可见。The messages returned from list_messages() becomes invisible to any other code reading messages from this queue. 将传递以秒为单位的可见性超时值作为参数。You pass in the visibility timeout in seconds as a parameter.
  2. 还必须调用 delete_message() ,才能完成队列消息删除操作。To finish removing the message from the queue, you must also call delete_message().

此删除消息的两步过程可确保当代码因硬件或软件故障而无法处理消息时,其他代码实例可以获取同一消息并重试。This two-step process of removing a message assures that when 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.

messages = azure_queue_service.list_messages("test-queue", 30)
azure_queue_service.delete_message("test-queue", 
  messages[0].id, messages[0].pop_receipt)

如何:更改已排队消息的内容How To: Change the Contents of a Queued Message

可以更改队列中现有消息的内容。You can change the contents of a message in-place in the queue. 以下代码使用 update_message() 方法来更新消息。The code below uses the update_message() method to update a message. 该方法将返回一个元组,其中包含队列消息的 pop 接收方,以及一个 UTC 日期时间值,表示消息会在队列中可见的时间。The method will return a tuple which contains the pop receipt of the queue message and a UTC date time value that represents when the message will be visible on the queue.

message = azure_queue_service.list_messages("test-queue", 30)
pop_receipt, time_next_visible = azure_queue_service.update_message(
  "test-queue", message.id, message.pop_receipt, "updated test message", 
  30)

如何:用于对消息取消排队的其他选项How To: Additional Options for Dequeuing Messages

可以通过两种方式自定义队列中的消息检索。There are two ways you can customize message retrieval from a queue.

  1. 可以获取一批消息。You can get a batch of message.
  2. 可以设置更长或更短的不可见超时时间,从而允许代码使用更多或更少的时间来完全处理每个消息。You can set a longer or shorter invisibility timeout, allowing your code more or less time to fully process each message.

以下代码示例使用 list_messages() 方法通过一次调用获取 15 条消息。The following code example uses the list_messages() method to get 15 messages in one call. 然后,它打印并删除每条消息。Then it prints and deletes each message. 它还将每条消息的不可见超时时间设置为 5 分钟。It also sets the invisibility timeout to five minutes for each message.

azure_queue_service.list_messages("test-queue", 300
  {:number_of_messages => 15}).each do |m|
  puts m.message_text
  azure_queue_service.delete_message("test-queue", m.id, m.pop_receipt)
end

如何:获取队列长度How To: Get the Queue Length

可以获取队列中消息数的估计值。You can get an estimation of the number of messages in the queue. get_queue_metadata() 方法要求队列服务返回有关队列的大概消息数和元数据。The get_queue_metadata() method asks the queue service to return the approximate message count and metadata about the queue.

message_count, metadata = azure_queue_service.get_queue_metadata(
  "test-queue")

如何:删除队列How To: Delete a Queue

若要删除队列及其中包含的所有消息,请对队列对象调用 delete_queue() 方法。To delete a queue and all the messages contained in it, call the delete_queue() method on the queue object.

azure_queue_service.delete_queue("test-queue")

后续步骤Next Steps

现在,已了解有关队列存储的基础知识,可单击下面的链接来了解更复杂的存储任务。Now that you've learned the basics of queue storage, follow these links to learn about more complex storage tasks.

若要了解 Azure 队列服务(本文所述)和 Azure 服务总线队列(如何使用服务总线队列文章中所述)之间的比较,请参阅 Azure 队列和服务总线队列 - 比较与对照For a comparison between the Azure Queue Service discussed in this article and Azure Service Bus Queues discussed in the How to use Service Bus Queues article, see Azure Queues and Service Bus Queues - Compared and Contrasted