How to Use Service Bus Queues
This guide will show you how to use Service Bus queues with PHP. The samples are written in PHP and use the Windows Azure SDK for PHP. The scenarios covered include creating queues, sending and receiving messages, and deleting queues.
Table of Contents
What are Service Bus Queues?
Service Bus Queues support a brokered messaging communication model. When using queues, components of a distributed application do not communicate directly with each other, they instead exchange messages via a queue, which acts as an intermediary. A message producer (sender) hands off a message to the queue and then continues its processing. Asynchronously, a message consumer (receiver) pulls the message from the queue and processes it. The producer does not have to wait for a reply from the consumer in order to continue to process and send further messages. Queues offer First In, First Out (FIFO) message delivery to one or more competing consumers. That is, messages are typically received and processed by the receivers in the order in which they were added to the queue, and each message is received and processed by only one message consumer.
Service Bus queues are a general-purpose technology that can be used for a wide variety of scenarios:
- Communication between web and worker roles in a multi-tier Windows Azure application
- Communication between on-premises apps and Windows Azure hosted apps in a hybrid solution
- Communication between components of a distributed application running on-premises in different organizations or departments of an organization
Using queues can enable you to scale out your applications better, and enable more resiliency to your architecture.
Create a Service Namespace
To begin using Service Bus queues in Windows Azure, you must first create a service namespace. A service namespace provides a scoping container for addressing Service Bus resources within your application.
To create a service namespace:
-
Log on to the Windows Azure Management Portal.
-
In the left navigation pane of the Management Portal, click Service Bus.
-
In the lower pane of the Management Portal, click Create.

-
In the Add a new namespace dialog, enter a namespace name. The system immediately checks to see if the name is available.

-
After making sure the namespace name is available, choose the country or region in which your namespace should be hosted (make sure you use the same country/region in which you are deploying your compute resources).
IMPORTANT: Pick the same region that you intend to choose for deploying your application. This will give you the best performance.
-
Click the check mark. The system now creates your service namespace and enables it. You might have to wait several minutes as the system provisions resources for your account.
The namespace you created will then appear in the Management Portal and takes a moment to activate. Wait until the status is Active before continuing.
Obtain the Default Management Credentials for the Namespace
In order to perform management operations, such as creating a queue, on the new namespace, you must obtain the management credentials for the namespace.
-
In the left navigation pane, click the Service Bus node, to display the list of available namespaces:

-
Select the namespace you just created from the list shown:

-
Click Access Key.

-
In the Connect to your namespace dialog, find the Default Issuer and Default Key entries. Make a note of these values, as you will use this information below to perform operations with the namespace.
Create a PHP application
The only requirement for creating a PHP application that accesses the Windows Azure Blob service is the referencing of classes in the Windows Azure SDK for PHP from within your code. You can use any development tools to create your application, including Notepad.
Note
Your PHP installation must also have the OpenSSL extension installed and enabled.
In this guide, you will use service features which can be called within a PHP application locally, or in code running within a Windows Azure web role, worker role, or web site.
Get the Windows Azure Client Libraries
Install via Composer
-
Install Git.
Note
On Windows, you will also need to add the Git executable to your PATH environment variable.
-
Create a file named composer.json in the root of your project and add the following code to it:
{
"require": {
"microsoft/windowsazure": "*"
},
"repositories": [
{
"type": "pear",
"url": "http://pear.php.net"
}
],
"minimum-stability": "dev"
} -
Download composer.phar in your project root.
-
Open a command prompt and execute this in your project root
php composer.phar install
Install manually
To download and install the PHP Client Libraries for Windows Azure manually, follow these steps:
-
Download a .zip archive that contains the libraries from GitHub. Alternatively, fork the repository and clone it to your local machine. (The latter option requires a GitHub account and having Git installed locally.)
-
Copy the WindowsAzure directory of the downloaded archive to your application directory structure.
For more information about installing the PHP Client Libraries for Windows Azure (including information about installing as a PEAR package), see Download the Windows Azure SDK for PHP.
To use the Windows Azure Servise Bus queue APIs, you need to:
- Reference the autoloader file using the require_once statement, and
- Reference any classes you might use.
The following example shows how to include the autoloader file and reference the ServicesBuilder class.
Note
This example (and other examples in this article) assume you have installed the PHP Client Libraries for Windows Azure via Composer. If you installed the libraries manually or as a PEAR package, you will need to reference the WindowsAzure.php autoloader file.
require_once 'vendor\autoload.php';
use WindowsAzure\Common\ServicesBuilder;
In the examples below, the require_once statement will be shown always, but only the classes necessary for the example to execute will be referenced.
Setup a Windows Azure Service Bus connection
To instantiate a Windows Azure Service Bus client you must first have a valid connection string following this format:
Endpoint=[yourEndpoint];SharedSecretIssuer=[Default Issuer];SharedSecretValue=[Default Key]
Where the Endpoint is typically of the format https://[yourNamespace].servicebus.windows.net.
To create any Windows Azure service client you need to use the ServicesBuilder class. You can:
- pass the connection string directly to it or
- use the CloudConfigurationManager (CCM)to check multiple external sources for the connection string:
- by default it comes with support for one external source - environmental variables
- you can add new sources by extending the ConnectionStringSource class
For the examples outlined here, the connection string will be passed directly.
require_once 'vendor\autoload.php';
use WindowsAzure\Common\ServicesBuilder;
$connectionString = "Endpoint=[yourEndpoint];SharedSecretIssuer=[Default Issuer];SharedSecretValue=[Default Key]";
$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);
How to: Create a queue
Management operations for Service Bus queues can be performed via the ServiceBusRestProxy class. A ServiceBusRestProxy object is constructed via the ServicesBuilder::createServiceBusService factory method with an appropriate connection string that encapsulates the token permissions to manage it.
The example below shows how to instantiate a ServiceBusRestProxy and call ServiceBusRestProxy->createQueue to create a queue named myqueue within a MySBNamespace service namespace:
require_once 'vendor\autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;
use WindowsAzure\ServiceBus\Models\QueueInfo;
// Create Service Bus REST proxy.
$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);
try {
$queueInfo = new QueueInfo("myqueue");
// Create queue.
$serviceBusRestProxy->createQueue($queueInfo);
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179357
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
} Note
You can use thelistQueuesmethod onServiceBusRestProxyobjects to check if a queue with a specified name already exists within a service namespace.
How to: Send messages to a queue
To send a message to a Service Bus queue, your application will call the ServiceBusRestProxy->sendQueueMessage method. The code below demonstrates how to send a message to the myqueue queue we created above within the MySBNamespace service namespace.
require_once 'vendor\autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;
use WindowsAzure\ServiceBus\models\BrokeredMessage;
// Create Service Bus REST proxy.
$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);
try {
// Create message.
$message = new BrokeredMessage();
$message->setBody("my message");
// Send message.
$serviceBusRestProxy->sendQueueMessage("myqueue", $message);
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/hh780775
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
} Messages sent to (and received from ) Service Bus queues are instances of the BrokeredMessage class. BrokeredMessage objects have a set of standard methods (such as getLabel, getTimeToLive, setLabel, and setTimeToLive) and properties that are used to hold custom application-specific properties, and a body of arbitrary application data.
Service Bus queues support a maximum message size of 256 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. This upper limit on queue size is 5 GB.
How to: Receive messages from a queue
The primary way to receive messages from a queue is to use a ServiceBusRestProxy->receiveQueueMessage method. Messages can be received in two different modes: ReceiveAndDelete (the default) and PeekLock.
When using the ReceiveAndDelete mode, receive is a single-shot operation - that is, when Service Bus receives a read request for a message in a queue, it marks the message as being consumed and returns it to the application. ReceiveAndDelete mode is 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 will have marked the message as being consumed, then when the application restarts and begins consuming messages again, it will have missed the message that was consumed prior to the crash.
In PeekLock mode, receiving a message becomes a two stage operation, which 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 from 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 passing the received message to ServiceBusRestProxy->deleteMessage. When Service Bus sees the deleteMessage call, it will mark the message as being consumed and remove it from the queue.
The example below demonstrates how a message can be received and processed using PeekLock mode (not the default mode).
require_once 'vendor\autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;
use WindowsAzure\ServiceBus\models\ReceiveMessageOptions;
// Create Service Bus REST proxy.
$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);
try {
// Set the receive mode to PeekLock (default is ReceiveAndDelete).
$options = new ReceiveMessageOptions();
$options->setPeekLock();
// Receive message.
$message = $serviceBusRestProxy->receiveQueueMessage("myqueue", $options);
echo "Body: ".$message->getBody()."<br />";
echo "MessageID: ".$message->getMessageId()."<br />";
/*---------------------------
Process message here.
----------------------------*/
// Delete message. Not necessary if peek lock is not set.
echo "Message deleted.<br />";
$serviceBusRestProxy->deleteMessage($message);
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/hh780735
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
} 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 unlockMessage method on the received message (instead of the deleteMessage method). This will cause 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 (e.g., if the application crashes), then Service Bus will unlock the message automatically and make it available to be received again.
In the event that the application crashes after processing the message but before the deleteMessage request is issued, then the message will be redelivered to the application when it restarts. This is often called At Least Once Processing, that is, each message will be processed at least once but in certain situations the same message may be redelivered. If the scenario cannot tolerate duplicate processing, then adding additional logic to your application to handle duplicate message delivery is recommended. This is often achieved using the getMessageId method of the message, which will remain constant across delivery attempts.
Next steps
Now that you've learned the basics of Service Bus queues, see the MSDN topic Queues, Topics, and Subscriptions for more information.