使用第 3 AWS SDK for PHP 版在 Amazon SQS 中啟用長輪詢 - AWS SDK for PHP

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用第 3 AWS SDK for PHP 版在 Amazon SQS 中啟用長輪詢

長輪詢可讓 Amazon SQS 在傳送回應之前等待訊息在佇列中可用的指定時間,藉此減少空白回應的數量。此外,長輪詢可查詢所有伺服器而非指查詢取樣的伺服器,來減少假的空白回應。若要啟用長輪詢,請針對接收的訊息指定非零的等待時間。如需進一步了解,請參閱 SQS 長輪詢

下列範例示範如何:

所有的範例程式碼都可以AWS SDK for PHP在這裡取得 GitHub。

登入資料

在執行範例程式碼之前,請依照中的說明設定您的AWS認證登入資料。然後匯入AWS SDK for PHP,如中所述基本使用

設定佇列上的屬性以啟用長輪詢

匯入

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sqs\SqsClient;

範例程式碼

$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->setQueueAttributes([ 'Attributes' => [ 'ReceiveMessageWaitTimeSeconds' => 20 ], 'QueueUrl' => $queueUrl, // REQUIRED ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

使用長輪詢檢索郵件

匯入

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sqs\SqsClient;

範例程式碼

$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->receiveMessage([ 'AttributeNames' => ['SentTimestamp'], 'MaxNumberOfMessages' => 1, 'MessageAttributeNames' => ['All'], 'QueueUrl' => $queueUrl, // REQUIRED 'WaitTimeSeconds' => 20, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

創建具有長輪詢的隊列

匯入

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sqs\SqsClient;

範例程式碼

$queueName = "QUEUE_NAME"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->createQueue([ 'QueueName' => $queueName, 'Attributes' => [ 'ReceiveMessageWaitTimeSeconds' => 20 ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }