在使用 Amazon SDK for PHP 版本 3 的 Amazon SQS 中发送和接收消息 - Amazon SDK for PHP
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在使用 Amazon SDK for PHP 版本 3 的 Amazon SQS 中发送和接收消息

要了解 Amazon SQS 消息,请参阅 Service Quotas 用户指南中的向 SQS 队列发送消息从 SQS 队列接收和删除消息

以下示例演示如何:

的所有示例代码都可以在此Amazon SDK for PHP处找到 GitHub

凭证

运行示例代码之前,请配置您的 Amazon 凭证,如 凭证 中所述。然后导入 Amazon SDK for PHP,如 基本用法 中所述。

发送消息

导入

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

示例代码

$client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); $params = [ 'DelaySeconds' => 10, 'MessageAttributes' => [ "Title" => [ 'DataType' => "String", 'StringValue' => "The Hitchhiker's Guide to the Galaxy" ], "Author" => [ 'DataType' => "String", 'StringValue' => "Douglas Adams." ], "WeeksOn" => [ 'DataType' => "Number", 'StringValue' => "6" ] ], 'MessageBody' => "Information about current NY Times fiction bestseller for week of 12/11/2016.", 'QueueUrl' => 'QUEUE_URL' ]; try { $result = $client->sendMessage($params); 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' => 0, ]); if (!empty($result->get('Messages'))) { var_dump($result->get('Messages')[0]); $result = $client->deleteMessage([ 'QueueUrl' => $queueUrl, // REQUIRED 'ReceiptHandle' => $result->get('Messages')[0]['ReceiptHandle'] // REQUIRED ]); } else { echo "No messages in queue. \n"; } } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }