On this tutorial, you learn to create PHP functions to ship messages to and obtain messages from a Service Bus queue.

Conditions

  1. An Azure subscription. To finish this tutorial, you want an Azure account. You possibly can activate your MSDN subscriber advantages or join a free account.
  2. If you do not have a queue to work with, comply with steps within the Use Azure portal to create a Service Bus queue article to create a queue.
    1. Learn the short overview of Service Bus queues.

    2. Create a Service Bus namespace.

    3. Get the connection string.

      Be aware

      You’ll create a queue within the Service Bus namespace through the use of PHP on this tutorial.

  3. Azure SDK for PHP

Create a PHP utility

The one requirement for making a PHP utility that accesses the Azure Blob service is the referencing of lessons within the Azure SDK for PHP from inside your code. You should use any improvement instruments to create your utility, or Notepad.

Be aware

Your PHP set up should even have the OpenSSL extension put in and enabled.

On this information, you’ll use service options, which could be known as from inside a PHP utility regionally, or in code working inside an Azure internet function, employee function, or web site.

Get the Azure consumer libraries

Set up by way of Composer

  1. Create a file named composer.json within the root of your mission and add the next code to it:

    {
      "require": {
        "microsoft/windowsazure": "*"
      }
    }
    
  2. Obtain composer.phar in your mission root.

  3. Open a command immediate and execute the next command in your mission root

    php composer.phar set up
    

Configure your utility to make use of Service Bus

To make use of the Service Bus queue APIs, do the next:

  1. Reference the autoloader file utilizing the require_once assertion.
  2. Reference any lessons you may use.

The next instance exhibits the best way to embrace the autoloader file and reference the ServicesBuilder class.

Be aware

This instance (and different examples on this article) assumes you could have put in the PHP Shopper Libraries for Azure by way of Composer. Should you put in the libraries manually or as a PEAR bundle, you will need to reference the WindowsAzure.php autoloader file.

require_once 'vendor/autoload.php';
use WindowsAzureCommonServicesBuilder;

Within the examples under, the require_once assertion will at all times be proven, however solely the lessons obligatory for the instance to execute are referenced.

Arrange a Service Bus connection

To instantiate a Service Bus consumer, you will need to first have a sound connection string on this format:

Endpoint=[yourEndpoint];SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[Primary Key]

The place Endpoint is usually of the format [yourNamespace].servicebus.home windows.web.

To create any Azure service consumer, you will need to use the ServicesBuilder class. You possibly can:

  • Cross the connection string on to it.
  • Use the CloudConfigurationManager (CCM) to test a number of exterior sources for the connection string:
    • By default it comes with assist for one exterior supply – environmental variables
    • You possibly can add new sources by extending the ConnectionStringSource class

For the examples outlined right here, the connection string is handed immediately.

require_once 'vendor/autoload.php';

use WindowsAzureCommonServicesBuilder;

$connectionString = "Endpoint=[yourEndpoint];SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[Primary Key]";

$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);

Create a queue

You possibly can carry out administration operations for Service Bus queues by way of the ServiceBusRestProxy class. A ServiceBusRestProxy object is constructed by way of the ServicesBuilder::createServiceBusService manufacturing unit methodology with an acceptable connection string that encapsulates the token permissions to handle it.

The next instance exhibits the best way to instantiate a ServiceBusRestProxy and name ServiceBusRestProxy->createQueue to create a queue named myqueue inside a MySBNamespace service namespace:

require_once 'vendor/autoload.php';

use WindowsAzureCommonServicesBuilder;
use WindowsAzureCommonServiceException;
use WindowsAzureServiceBusModelsQueueInfo;

// Create Service Bus REST proxy.
$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);

attempt    {
    $queueInfo = new QueueInfo("myqueue");

    // Create queue.
    $serviceBusRestProxy->createQueue($queueInfo);
}
catch(ServiceException $e){
    // Deal with exception primarily based on error codes and messages.
    // Error codes and messages are right here: 
    // https://docs.microsoft.com/relaxation/api/storageservices/Widespread-REST-API-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."
"; }

Be aware

You should use the listQueues methodology on ServiceBusRestProxy objects to test if a queue with a specified identify already exists inside a namespace.

Ship messages to a queue

To ship a message to a Service Bus queue, your utility calls the ServiceBusRestProxy->sendQueueMessage methodology. The next code exhibits the best way to ship a message to the myqueue queue beforehand created throughout the
MySBNamespace service namespace.

require_once 'vendor/autoload.php';

use WindowsAzureCommonServicesBuilder;
use WindowsAzureCommonServiceException;
use WindowsAzureServiceBusModelsBrokeredMessage;

// Create Service Bus REST proxy.
$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);

attempt    {
    // Create message.
    $message = new BrokeredMessage();
    $message->setBody("my message");

    // Ship message.
    $serviceBusRestProxy->sendQueueMessage("myqueue", $message);
}
catch(ServiceException $e){
    // Deal with exception primarily based on error codes and messages.
    // Error codes and messages are right here: 
    // https://docs.microsoft.com/relaxation/api/storageservices/Widespread-REST-API-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."
"; }

Messages despatched to (and acquired from) Service Bus queues are cases of the BrokeredMessage class. BrokeredMessage objects have a set of ordinary strategies and properties which might be used to carry customized application-specific properties, and a physique of arbitrary utility information.

Service Bus queues assist a most message measurement of 256 KB within the Commonplace tier and 1 MB within the Premium tier. The header, which incorporates the usual and customized utility properties, can have
a most measurement of 64 KB. There isn’t a restrict on the variety of messages held in a queue however there’s a cap on the entire measurement of the messages held by a queue. This higher restrict on queue measurement is 5 GB.

Obtain messages from a queue

One of the best ways to obtain messages from a queue is to make use of a ServiceBusRestProxy->receiveQueueMessage methodology. Messages could be acquired in two completely different modes: ReceiveAndDelete and PeekLock. PeekLock is the default.

When utilizing ReceiveAndDelete mode, obtain is a single-shot operation; that’s, when Service Bus receives a learn request for a message in a queue, it marks the message as being consumed and returns it to the applying. ReceiveAndDelete mode is the best mannequin and works finest for situations wherein an utility can tolerate not processing a message within the occasion of a failure. To know this, contemplate a situation wherein the buyer points the obtain request after which crashes earlier than processing it. As a result of Service Bus can have marked the message as being consumed, then when the applying restarts and begins consuming messages once more, it’s going to have missed the message that was consumed previous to the crash.

Within the default PeekLock mode, receiving a message turns into a two stage operation, which makes it doable to assist functions that can’t tolerate lacking messages. When Service Bus receives a request, it finds the following message to be consumed, locks it to forestall different customers from receiving it, after which returns it to the applying. After the applying finishes processing the message (or shops it reliably for future processing), it completes the second stage of the obtain course of by passing the acquired message to ServiceBusRestProxy->deleteMessage. When Service Bus sees the deleteMessage name, it’s going to mark the message as being consumed and take away it from the queue.

The next instance exhibits the best way to obtain and course of a message utilizing PeekLock mode (the default mode).

require_once 'vendor/autoload.php';

use WindowsAzureCommonServicesBuilder;
use WindowsAzureCommonServiceException;
use WindowsAzureServiceBusModelsReceiveMessageOptions;

// Create Service Bus REST proxy.
$serviceBusRestProxy = ServicesBuilder::getInstance()->createServiceBusService($connectionString);

attempt    {
    // Set the obtain mode to PeekLock (default is ReceiveAndDelete).
    $choices = new ReceiveMessageOptions();
    $options->setPeekLock();

    // Obtain message.
    $message = $serviceBusRestProxy->receiveQueueMessage("myqueue", $choices);
    echo "Physique: ".$message->getBody()."
"; echo "MessageID: ".$message->getMessageId()."
"; /*--------------------------- Course of message right here. ----------------------------*/ // Delete message. Not obligatory if peek lock just isn't set. echo "Message deleted.
"; $serviceBusRestProxy->deleteMessage($message); } catch(ServiceException $e){ // Deal with exception primarily based on error codes and messages. // Error codes and messages are right here: // https://docs.microsoft.com/relaxation/api/storageservices/Widespread-REST-API-Error-Codes $code = $e->getCode(); $error_message = $e->getMessage(); echo $code.": ".$error_message."
"; }

Methods to deal with utility crashes and unreadable messages

Service Bus supplies performance that can assist you gracefully get well from errors in your utility or difficulties processing a message. If a receiver utility is unable to course of the message for some cause, then it will possibly name the unlockMessage methodology on the acquired message (as a substitute of the deleteMessage methodology). This can trigger Service Bus to unlock the message throughout the queue and make it accessible to be acquired once more, both by the identical consuming utility or by one other consuming utility.

There’s additionally a timeout related to a message locked throughout the queue, and if the applying fails to course of the message earlier than the lock timeout expires (for instance, if the applying crashes), then Service Bus will unlock the message robotically and make it accessible to be acquired once more.

Within the occasion that the applying crashes after processing the message however earlier than the deleteMessage request is issued, then the message shall be redelivered to the applying when it restarts. That is usually known as At Least As soon as processing; that’s, every message is processed no less than as soon as however in sure conditions the identical message could also be redelivered. If the situation can not tolerate duplicate processing, then including further logic to functions to deal with duplicate message supply is beneficial. That is usually achieved utilizing the getMessageId methodology of the message, which stays fixed throughout supply makes an attempt.

Be aware

You possibly can handle Service Bus sources with Service Bus Explorer. The Service Bus Explorer permits customers to connect with a Service Bus namespace and administer messaging entities in a straightforward method. The software supplies superior options like import/export performance or the flexibility to check matter, queues, subscriptions, relay companies, notification hubs and occasions hubs.

Subsequent steps

Now that you’ve got realized the fundamentals of Service Bus queues, see Queues, subjects, and subscriptions for extra data.

For extra data, additionally go to the PHP Developer Heart.

Leave a Reply

Your email address will not be published. Required fields are marked *