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

在本教學課程中,您將了解如何建立 PHP 應用程式以對服務匯流排佇列傳送和接收訊息。In this tutorial, you learn how to create PHP applications to send messages to and receive messages from a Service Bus queue.

必要條件Prerequisites

  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 入口網站建立服務匯流排佇列一文中的步驟,以建立佇列。If you don't have a queue to work with, follow steps in the Use Azure portal to create a Service Bus queue article to create a queue.
    1. 閱讀服務匯流排 佇列 的快速 概觀Read the quick overview of Service Bus queues.

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

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

      注意

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

  3. Azure SDK for PHPAzure SDK for PHP

建立 PHP 應用程式Create a PHP application

建立存取 Azure Blob 服務之 PHP 應用程式的唯一需求,就是在您的程式碼中參考 AZURE SDK FOR PHP 中的類別。The only requirement for creating a PHP application that accesses the Azure Blob service is the referencing of classes in the Azure SDK for PHP from within your code. 您可以使用任何開發工具來建立應用程式,或記事本。You can use any development tools to create your application, or Notepad.

注意

您的 PHP 安裝也必須已安裝並啟用 OpenSSL 延伸模組Your PHP installation must also have the OpenSSL extension installed and enabled.

在本指南中,您將使用可從 PHP 應用程式內本機呼叫的服務功能,或可從 Azure Web 角色、背景工作角色或網站內執行的程式碼中呼叫的資料表服務功能。In this guide, you will use service features, which can be called from within a PHP application locally, or in code running within an Azure web role, worker role, or website.

取得 Azure 用戶端程式庫Get the Azure client libraries

透過編輯器安裝Install via Composer

  1. 在專案的根目錄中,建立名為 composer.js 的檔案,並在其中新增下列程式碼:Create a file named composer.json in the root of your project and add the following code to it:

    {
      "require": {
        "microsoft/windowsazure": "*"
      }
    }
    
  2. composer.phar 下載到專案根目錄中。Download composer.phar in your project root.

  3. 開啟命令提示字元,在專案根目錄中執行下列命令Open a command prompt and execute the following command in your project root

    php composer.phar install
    

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

若要使用服務匯流排佇列 API,請執行下列動作:To use the Service Bus queue APIs, do the following:

  1. 使用 require_once 陳述式來參考自動換片器檔案。Reference the autoloader file using the require_once statement.
  2. 參考任何您可能使用的類別。Reference any classes you might use.

下列範例顯示如何納入自動換片器檔案及參考 ServicesBuilder 類別。The following example shows how to include the autoloader file and reference the ServicesBuilder class.

注意

此範例 (和本文中的其他範例) 假設您已透過編輯器安裝 PHP Client Libraries for Azure。This example (and other examples in this article) assumes you have installed the PHP Client Libraries for Azure via Composer. 如果您以手動方式或以 PEAR 套件方式安裝程式庫,則必須參考 WindowsAzure.php 自動換片器檔案。If you installed the libraries manually or as a PEAR package, you must reference the WindowsAzure.php autoloader file.

require_once 'vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;

在下列各範例中,一律會顯示 require_once 陳述式,但只會參考要執行之範例所需的類別。In the examples below, the require_once statement will always be shown, but only the classes necessary for the example to execute are referenced.

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

若要具現化服務匯流排用戶端,您必須具備符合下列格式的有效連接字串:To instantiate a Service Bus client, you must first have a valid connection string in this format:

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

其中,Endpoint 的格式通常是 [yourNamespace].servicebus.windows.netWhere Endpoint is typically of the format [yourNamespace].servicebus.windows.net.

若要建立任何 Azure 服務用戶端,您必須使用 ServicesBuilder 類別。To create any Azure service client, you must use the ServicesBuilder class. 您可以:You can:

  • 直接將連接字串傳遞給它。Pass the connection string directly to it.
  • 使用 CloudConfigurationManager (CCM) 來檢查連接字串的多個外部來源: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
    • 您可以擴充 ConnectionStringSource 類別以加入新來源You can add new sources by extending the ConnectionStringSource class

在本文的各範例中,將會直接傳遞連接字串。For the examples outlined here, the connection string is passed directly.

require_once 'vendor/autoload.php';

use WindowsAzure\Common\ServicesBuilder;

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

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

建立佇列Create a queue

您可以使用 ServiceBusRestProxy 類別來執行服務匯流排佇列的管理作業。You can perform management operations for Service Bus queues via the ServiceBusRestProxy class. ServiceBusRestProxy 物件可透過 ServicesBuilder::createServiceBusService Factory 方法,使用含有權杖權限加以管理的適當連接字串來建構。A ServiceBusRestProxy object is constructed via the ServicesBuilder::createServiceBusService factory method with an appropriate connection string that encapsulates the token permissions to manage it.

下列範例將說明如何具現化 ServiceBusRestProxy 並呼叫 ServiceBusRestProxy->createQueue,以便在 MySBNamespace 服務命名空間內建立名為 myqueue 的佇列:The following example 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: 
    // https://docs.microsoft.com/rest/api/storageservices/Common-REST-API-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

注意

您可以在 ServiceBusRestProxy 物件上使用 listQueues 方法,來檢查命名空間內是否已有指定名稱的佇列存在。You can use the listQueues method on ServiceBusRestProxy objects to check if a queue with a specified name already exists within a namespace.

傳送訊息至佇列Send messages to a queue

若要將訊息傳送至服務匯流排佇列,應用程式會呼叫 ServiceBusRestProxy->sendQueueMessage 方法。To send a message to a Service Bus queue, your application calls the ServiceBusRestProxy->sendQueueMessage method. 下列程式碼示範如何將訊息傳送至先前在 MySBNamespace 服務命名空間中建立的 myqueue 佇列。The following code shows how to send a message to the myqueue queue previously created 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: 
    // https://docs.microsoft.com/rest/api/storageservices/Common-REST-API-Error-Codes
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

傳送至 (並從) 服務匯流排佇列接收的訊息是 BrokeredMessage 類別的實例。Messages sent to (and received from) Service Bus queues are instances of the BrokeredMessage class. BrokeredMessage 物件具有一組標準方法和屬性,可用來保存自訂的應用程式特定屬性,以及任意的應用程式資料。BrokeredMessage objects have a set of standard methods and properties that are used to hold custom application-specific properties, and a body of arbitrary application data.

服務匯流排佇列支援的訊息大小上限:在標準層中為 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 upper limit on queue size is 5 GB.

從佇列接收訊息Receive messages from a queue

從佇列接收訊息的最佳方式是使用 ServiceBusRestProxy->receiveQueueMessage 方法。The best way to receive messages from a queue is to use a ServiceBusRestProxy->receiveQueueMessage method. 訊息可以兩種不同的模式接收: >receiveanddeletePeekLockMessages can be received in two different modes: ReceiveAndDelete and PeekLock. PeekLock 是預設值。PeekLock is the default.

使用 ReceiveAndDelete 模式時,接收是單發作業;也就是說,當服務匯流排收到佇列中訊息的讀取要求時,它會將此訊息標示為已使用,並將它傳回應用程式。When using 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 模式是最簡單的模型,且最適合可容許在發生失敗時不處理訊息的應用程式案例。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.

在預設的 PeekLock 模式中,接收訊息會變成兩階段作業,因此可以支援無法容許遺漏訊息的應用程式。In the default 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. 在應用程式完成處理訊息 (或可靠地儲存此訊息以供未來處理) 之後,它會將已接收的訊息傳遞至 ServiceBusRestProxy->deleteMessage,以完成接收程序的第二個階段。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. 當服務匯流排看到 deleteMessage 呼叫時,它會將訊息標示為已取用,並將它從佇列中移除。When Service Bus sees the deleteMessage call, it will mark the message as being consumed and remove it from the queue.

下列範例說明如何使用 PeekLock 模式 (預設模式) 來接收與處理訊息。The following example shows how to receive and process a message using PeekLock mode (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:
    // https://docs.microsoft.com/rest/api/storageservices/Common-REST-API-Error-Codes
    $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. 如果接收者應用程式因為某些原因無法處理訊息,它可以在接收訊息上呼叫 unlockMessage 方法 (而不是 deleteMessage 方法)。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 (for example, if the application crashes), then Service Bus will unlock the message automatically and make it available to be received again.

如果應用程式在處理訊息之後,但尚未發出 deleteMessage 要求時當機,則會在應用程式重新啟動時將訊息重新傳遞給該應用程式。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 is 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 applications to handle duplicate message delivery is recommended. 通常您可使用訊息的 getMessageId 方法來達到此目的,該方法在各個傳遞嘗試中保持不變。This is often achieved using the getMessageId method 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, see Queues, topics, and subscriptions for more information.

如需詳細資訊,另請造訪 PHP 開發人員中心For more information, also visit the PHP Developer Center.