快速入門:如何搭配 Ruby 使用服務匯流排佇列Quickstart: How to use Service Bus queues with Ruby

在本教學課程中,您將了解如何建立 Ruby 應用程式以對服務匯流排佇列傳送和接收訊息。In this tutorial, you learn how to create Ruby applications to send messages to and receive messages from a Service Bus queue. 這些範例均以 Ruby 撰寫,並使用 Azure gem。The samples are written in Ruby and use the Azure gem.


  1. Azure 訂用帳戶。An Azure subscription. 若要完成此教學課程,您需要 Azure 帳戶。To complete this tutorial, you need an Azure account. 您可以啟用自己的 MSDN 訂戶權益或是註冊免費帳戶You can activate your MSDN subscriber benefits or sign up for a free account.
  2. 執行使用 Azure 入口網站建立服務匯流排佇列一文中的步驟。Follow steps in the Use Azure portal to create a Service Bus queue article.
    1. 閱讀服務匯流排 佇列 的快速 概觀Read the quick overview of Service Bus queues.

    2. 建立服務匯流排 命名空間Create a Service Bus namespace.

    3. 取得 連接字串Get the connection string.


      您將在本教學課程中使用 Ruby,在服務匯流排命名空間中建立 佇列You will create a queue in the Service Bus namespace by using Ruby in this tutorial.

建立 Ruby 應用程式Create a Ruby application

如需指示,請參閱在 Azure 上建立 Ruby 應用程式For instructions, see Create a Ruby Application on Azure.

設定應用程式以使用服務匯流排Configure Your application to Use Service Bus

若要使用服務匯流排,請下載並使用 Azure Ruby 套件,其中包含一組能與儲存體 REST 服務通訊的便利程式庫。To use Service Bus, download and use the Azure Ruby 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 檔案頂端:Using your favorite text editor, add the following to the top of the Ruby file in which you intend to use storage:

require "azure"

設定服務匯流排連接Set up a Service Bus connection

您可以使用下列程式碼來設定命名空間、金鑰名稱、金鑰、簽署者和主機的值︰Use the following code to set the values of namespace, name of the key, key, signer and host:

Azure.configure do |config|
  config.sb_namespace = '<your azure service bus namespace>'
  config.sb_sas_key_name = '<your azure service bus access keyname>'
  config.sb_sas_key = '<your azure service bus access key>'
signer = Azure::ServiceBus::Auth::SharedAccessSigner.new
sb_host = "https://#{Azure.sb_namespace}.servicebus.windows.net"

將命名空間值設為您建立的值而非整個 URL。Set the namespace value to the value you created rather than the entire URL. 例如,使用 "yourexamplenamespace" 而非 "yourexamplenamespace.servicebus.windows.net"。For example, use "yourexamplenamespace", not "yourexamplenamespace.servicebus.windows.net".

使用多個命名空間時,您可以在建立 SharedAccessSigner 物件時,將索引鍵和其名稱傳遞至建構函式When working with multiple namespaces, you can pass the key and its name to the constructor while creating SharedAccessSigner objects

sb_namespace = '<your azure service bus namespace>'
sb_sas_key_name = '<your azure service bus access keyname>'
sb_sas_key = '<your azure service bus access key>'

signer = Azure::ServiceBus::Auth::SharedAccessSigner.new(sb_sas_key_name, sb_sas_key)
sb_host = "https://#{sb_namespace}.servicebus.windows.net"

如何建立佇列How to create a queue

Azure::ServiceBusService 物件可讓您使用佇列。The Azure::ServiceBusService object enables you to work with queues. 若要建立佇列,請使用 create_queue() 方法。To create a queue, use the create_queue() method. 下列範例會建立佇列,或列印出任何錯誤。The following example creates a queue or prints out any errors.

azure_service_bus_service = Azure::ServiceBus::ServiceBusService.new(sb_host, { signer: signer})
  queue = azure_service_bus_service.create_queue("test-queue")
  puts $!

您也可以使用其他選項傳遞 Azure::ServiceBus::Queue 物件,這可讓您覆寫訊息存留時間或佇列大小上限等預設佇列設定。You can also pass a Azure::ServiceBus::Queue object with additional options, which enables you to override the default queue settings, such as message time to live or maximum queue size. 下列範例說明如何將佇列大小上限設為 5 GB,將存留時間設為 1 分鐘:The following example shows how to set the maximum queue size to 5 GB and time to live to 1 minute:

queue = Azure::ServiceBus::Queue.new("test-queue")
queue.max_size_in_megabytes = 5120
queue.default_message_time_to_live = "PT1M"

queue = azure_service_bus_service.create_queue(queue)

如何傳送訊息至佇列How to send messages to a queue

若要傳送訊息至服務匯流排佇列,應用程式將呼叫 Azure::ServiceBusService 物件上的 send_queue_message() 方法。To send a message to a Service Bus queue, your application calls the send_queue_message() method on the Azure::ServiceBusService object. 傳送至 (及接收自)「服務匯流排」佇列的訊息是 Azure::ServiceBus::BrokeredMessage 物件,而且具有一組標準屬性 (例如 labeltime_to_live)、一個用來保存自訂應用程式特定屬性的字典,以及一堆任意的應用程式資料。Messages sent to (and received from) Service Bus queues are Azure::ServiceBus::BrokeredMessage objects, and have a set of standard properties (such as label and time_to_live), a dictionary that is used to hold custom application-specific properties, and a body of arbitrary application data. 應用程式可用訊息的形式傳遞字串值以設定訊息內文,任何必要的標準屬性都會以預設值填入。An application can set the body of the message by passing a string value as the message and any required standard properties are populated with default values.

下列範例示範如何使用 send_queue_message() 將測試訊息傳送至名為 test-queue 的佇列:The following example demonstrates how to send a test message to the queue named test-queue using send_queue_message():

message = Azure::ServiceBus::BrokeredMessage.new("test queue message")
message.correlation_id = "test-correlation-id"
azure_service_bus_service.send_queue_message("test-queue", message)

服務匯流排佇列支援的訊息大小上限:在標準層中為 256 KB 以及在進階層中為 1 MB。Service Bus queues support a maximum message size of 256 KB in the Standard tier and 1 MB in the Premium tier. 標頭 (包含標準和自訂應用程式屬性) 可以容納 64 KB 的大小上限。The header, which includes the standard and custom application properties, can have a maximum size of 64 KB. 佇列中所保存的訊息數目沒有限制,但佇列所保存的訊息大小總計會有最高限制。There is no limit on the number of messages held in a queue but there is a cap on the total size of the messages held by a queue. 此佇列大小會在建立時定義,上限是 5 GB。This queue size is defined at creation time, with an upper limit of 5 GB.

如何從佇列接收訊息How to receive messages from a queue

對於 Azure::ServiceBusService 物件使用 receive_queue_message() 方法即可從佇列接收訊息。Messages are received from a queue using the receive_queue_message() method on the Azure::ServiceBusService object. 根據預設,在讀取及鎖定訊息後並不會將其從佇列中刪除。By default, messages are read and locked without being deleted from the queue. 但您可以將 :peek_lock 選項設為 false,而在讀取訊息後將其從佇列中刪除。However, you can delete messages from the queue as they are read by setting the :peek_lock option to false.

預設行為會使讀取和刪除變成兩階段作業,因此也可以支援無法容許遺漏訊息的應用程式。The default behavior makes the reading and deleting a two-stage operation, which also makes it possible to support applications that cannot tolerate missing messages. 當服務匯流排收到要求時,它會尋找要取用的下一個訊息、將其鎖定以防止其他取用者接收此訊息,然後將它傳回應用程式。When Service Bus receives a request, it finds the next message to be consumed, locks it to prevent other consumers receiving it, and then returns it to the application. 在應用程式完成處理訊息 (或可靠地儲存此訊息以供未來處理) 之後,它可透過呼叫 delete_queue_message() 方法和以參數形式提供要刪除的訊息,完成接收程序的第二個階段。After the application finishes processing the message (or stores it reliably for future processing), it completes the second stage of the receive process by calling delete_queue_message() method and providing the message to be deleted as a parameter. delete_queue_message() 方法會將訊息標示為已取用,並將其從佇列中移除。The delete_queue_message() method will mark the message as being consumed and remove it from the queue.

如果 :peek_lock 參數設為 false,讀取和刪除訊息將會變成最簡單的模型,且最適用於應用程式容許在發生失敗時不處理訊息的案例。If the :peek_lock parameter is set to false, reading, and deleting the message becomes the simplest model, and works best for scenarios in which an application can tolerate not processing a message in the event of a failure. 若要了解這一點,請考慮取用者發出接收要求,接著系統在處理此要求之前當機的案例。To understand this, consider a scenario in which the consumer issues the receive request and then crashes before processing it. 因為服務匯流排已將訊息標示為已取用,當應用程式重新啟動並開始重新取用訊息時,它將會遺漏當機前已取用的訊息。Because Service Bus has marked the message as being consumed, when the application restarts and begins consuming messages again, it will have missed the message that was consumed prior to the crash.

下列範例示範如何使用 receive_queue_message() 來接收和處理訊息。The following example demonstrates how to receive and process messages using receive_queue_message(). 此範例會先使用設為 false:peek_lock 來接收及刪除訊息,然後再接收另一個訊息,接著使用 delete_queue_message() 刪除訊息:The example first receives and deletes a message by using :peek_lock set to false, then it receives another message and then deletes the message using delete_queue_message():

message = azure_service_bus_service.receive_queue_message("test-queue",
  { :peek_lock => false })
message = azure_service_bus_service.receive_queue_message("test-queue")

如何處理應用程式當機與無法讀取的訊息How to handle application crashes and unreadable messages

服務匯流排提供一種功能,可協助您從應用程式的錯誤或處理訊息的問題中順利復原。Service Bus provides functionality to help you gracefully recover from errors in your application or difficulties processing a message. 如果接收者應用程式因為某些原因無法處理訊息,它可以呼叫 Azure::ServiceBusService 物件上的 unlock_queue_message() 方法。If a receiver application is unable to process the message for some reason, then it can call the unlock_queue_message() method on the Azure::ServiceBusService object. 此呼叫將導致服務匯流排將佇列中的訊息解除鎖定,讓此訊息可以被相同取用應用程式或其他取用應用程式重新接收。This call causes Service Bus to unlock the message within the queue and make it available to be received again, either by the same consuming application or by another consuming application.

與在佇列內鎖定訊息相關的還有逾時,如果應用程式無法在鎖定逾時到期之前處理訊息 (例如,如果應用程式當機),則服務匯流排會自動解除鎖定訊息,並讓訊息可以被重新接收。There is also a timeout associated with a message locked within the queue, and if the application fails to process the message before the lock timeout expires (for example, if the application crashes), then Service Bus unlocks the message automatically and makes it available to be received again.

如果應用程式在處理訊息之後,尚未呼叫 delete_queue_message() 方法時當機,則會在應用程式重新啟動時將訊息重新傳遞給該應用程式。In the event that the application crashes after processing the message but before the delete_queue_message() method is called, then the message is redelivered to the application when it restarts. 此程式通常至少會被呼叫 一次,也就是說,每個訊息至少會被處理一次,但在特定狀況下,可能會重新傳遞相同訊息。This process is often called At Least Once Processing; that is, each message is processed at least once but in certain situations the same message may be redelivered. 如果案例無法容許重複處理,則應用程式開發人員應在其應用程式中加入其他邏輯,以處理重複的訊息傳遞。If the scenario cannot tolerate duplicate processing, then application developers should add additional logic to their application to handle duplicate message delivery. 通常您可使用訊息的 message_id 屬性來達到此目的,該方法在各個傳遞嘗試中保持不變。This is often achieved using the message_id property of the message, which remains constant across delivery attempts.


您可以使用服務匯流排總管來管理服務匯流排資源。You can manage Service Bus resources with Service Bus Explorer. 服務匯流排總管可讓使用者連線到服務匯流排命名空間,並以簡便的方式管理傳訊實體。The Service Bus Explorer allows users to connect to a Service Bus namespace and administer messaging entities in an easy manner. 此工具提供進階的功能 (例如匯入/匯出功能) 或測試主題、佇列、訂用帳戶、轉送服務、通知中樞和事件中樞的能力。The tool provides advanced features like import/export functionality or the ability to test topic, queues, subscriptions, relay services, notification hubs and events hubs.

後續步驟Next steps

了解基本的服務匯流排佇列之後,請參考下列連結以取得更多資訊。Now that you've learned the basics of Service Bus queues, follow these links to learn more.

若要比較本文所討論的 Azure 服務匯流排佇列與如何使用 Ruby 的佇列儲存體一文中討論的 Azure 佇列,請參閱 Azure 佇列和 Azure 服務匯流排佇列 - 比較和對照For a comparison between the Azure Service Bus queues discussed in this article and Azure Queues discussed in the How to use Queue storage from Ruby article, see Azure Queues and Azure Service Bus Queues - Compared and Contrasted