Quickstart: How to use Service Bus queues with Ruby

In this tutorial, you learn how to create Ruby applications to send messages to and receive messages from a Service Bus queue. The samples are written in Ruby and use the Azure gem.

Prerequisites

  1. An Azure subscription. To complete this tutorial, you need an Azure account. You can activate your MSDN subscriber benefits or sign up for a free account.
  2. 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.

      Note

      You will create a queue in the Service Bus namespace by using Ruby in this tutorial.

Create a Ruby application

For instructions, see Create a Ruby Application on Azure.

Configure Your application to Use Service Bus

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.

Use RubyGems to obtain the package

  1. Use a command-line interface such as PowerShell (Windows), Terminal (Mac), or Bash (Unix).
  2. Type "gem install azure" in the command window to install the gem and dependencies.

Import the package

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>'
end
signer = Azure::ServiceBus::Auth::SharedAccessSigner.new
sb_host = "https://#{Azure.sb_namespace}.servicebus.windows.net"

Set the namespace value to the value you created rather than the entire URL. For example, use "yourexamplenamespace", not "yourexamplenamespace.servicebus.windows.net".

How to create a queue

The Azure::ServiceBusService object enables you to work with queues. 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})
begin
  queue = azure_service_bus_service.create_queue("test-queue")
rescue
  puts $!
end

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. 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

To send a message to a Service Bus queue, your application calls the send_queue_message() method on the Azure::ServiceBusService object. 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.

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)

Service Bus queues support a maximum message size of 256 KB in the Standard tier and 1 MB in the Premium tier. 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. This queue size is defined at creation time, with an upper limit of 5 GB.

How to receive messages from a queue

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. 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. 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. The delete_queue_message() method will mark the message as being consumed and remove it from the queue.

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.

The following example demonstrates how to receive and process messages using receive_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")
azure_service_bus_service.delete_queue_message(message)

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. 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.

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. This is often achieved using the message_id property of the message, which remains constant across delivery attempts.

Note

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.

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