Example of using Yandex Message Queue on PHP
With AsyncAws
Installation
Install the AsyncAws library:
composer require async-aws/sqs ^1.9
Getting started
- Create a service account.
- Assign the editor role to the service account.
- Create a static access key.
Set the environment variables:
export AWS_ACCESS_KEY_ID="<access_key_ID>"
export AWS_SECRET_ACCESS_KEY="<secret_key>"
Example
In this example:
- A connection with Message Queue is established.
- A message queue is created with the
mq_php_sdk_example
name. - A message with the text
test-message
is sent to the queue. - The message is read from the queue and displayed in the terminal.
- The message queue is deleted.
<?php
use AsyncAws\Sqs\SqsClient;
require __DIR__ . '/vendor/autoload.php';
$mq = new SqsClient([
'region' => 'ru-central1',
'endpoint' => 'https://message-queue.api.cloud.yandex.net',
]);
$result = $mq->createQueue([
'QueueName' => 'mq_php_sdk_example',
]);
$queueUrl = $result->getQueueUrl();
print('Queue created, URL: ' . $queueUrl . PHP_EOL);
$result = $mq->sendMessage([
'QueueUrl' => $queueUrl,
'MessageBody' => 'Test message',
]);
print("Message sent, ID: " . $result->getMessageId() . PHP_EOL);
$result = $mq->receiveMessage([
'QueueUrl' => $queueUrl,
'WaitTimeSeconds' => 10,
]);
foreach ($result->getMessages() as $msg) {
print('Message received:' . PHP_EOL);
print('ID: ' . $msg->getMessageId() . PHP_EOL);
print('Body: ' . $msg->getBody() . PHP_EOL);
$mq->deleteMessage([
'QueueUrl' => $queueUrl,
'ReceiptHandle' => $msg->getReceiptHandle(),
]);
}
$result = $mq->deleteQueue([
'QueueUrl' => $queueUrl,
]);
print('Queue deleted' . PHP_EOL);