This topic describes how to use the SDK for PHP to create a topic, create a queue, create a subscription, and publish a message.
Step 1: Make preparations
- Download the CreateTopicAndPushMessageToQueue file.
- Open the CreateTopicAndSendMessage.php file and specify the following information:
- AccessKey ID and AccessKey secret
- The AccessKey pair that is used to call Alibaba Cloud API operations.
- If you use an Alibaba Cloud account, go to the AccessKey Management page of the Alibaba Cloud Management Console to create and view an AccessKey pair.
- If you use a RAM user, log on to the Resource Access Management (RAM) console to view the AccessKey pair.
- Endpoint
- The endpoint that is used to access Message Service (MNS). To view the endpoints of MNS, log on to the MNS console. For more information, see View the endpoints of a topic.
- The endpoint of MNS varies based on the region.
- AccessKey ID and AccessKey secret
- Modify the SDK
Use the sample code at the beginning of the CreateTopicAndSendMessage.php file to configure the SDK.
// Import an SDK autoload file. require __DIR__ . '/vendor/autoload.php'; // Declare the required PHP classes. use AliyunMNS\Client; use AliyunMNS\Exception\MessageNotExistException; use AliyunMNS\Model\SubscriptionAttributes; use AliyunMNS\Requests\PublishMessageRequest; use AliyunMNS\Requests\CreateTopicRequest; use AliyunMNS\Requests\CreateQueueRequest; use AliyunMNS\Exception\MnsException;
Step 2: Create a topic
If no topic is available, you must create a topic. By default, a topic named CreateTopicAndPushMessageToQueueExample and a queue named CreateTopicAndPushMessageToQueueExample are created. You can change the topic name and queue name in the code.
// Generate an instance named CreateTopicRequest and configure the topicName parameter. You can also configure the TopicAttributes parameter to specify properties for the topic that you want to create.
$request = new CreateTopicRequest($topicName);
try {
$res = $this->client->createTopic($request);
echo "TopicCreated! \n";
} catch (MnsException $e) {
// The topic may fail to be created if a network error occurs or the topic name already exists. You can call the CatchException operation to identify and resolve the issue.
echo "CreateTopicFailed: " . $e;
return;
}
Step 3: Create a queue
If no queue is available, you must create a queue. By default, a queue named CreateQueueAndSendMessageExample is created. You can change the queue name in the code.
// Generate an object named CreateQueueRequest. You can configure QueueAttributes parameter for the CreateQueueRequest object to initialize the properties of the queue.
// For more information about the properties of the queue, see Queue.
$request = new CreateQueueRequest($queueName);
try {
$res = $this->client->createQueue($request);
echo "QueueCreated! \n";
} catch (MnsException $e) {
// The queue may fail to be created if a network error occurs or the queue name already exists. You can call the CatchException operation to identify and resolve the issue.
echo "CreateQueueFailed: " . $e;
return;
}
Step 4: Create a subscription
Create a subscription to the topic.
$subscriptionName = "SubscriptionExample";
$attributes = new SubscriptionAttributes($subscriptionName, $topic->generateQueueEndpoint($queueName), 'BACKOFF_RETRY', 'SIMPLIFIED');
try {
$topic->subscribe($attributes);
echo "Subscribed! \n";
} catch (MnsException $e) {
// The subscription may fail to be created if a network error occurs or the subscription name already exists. You can call the CatchException operation to identify and resolve the issue.
echo "SubscribeFailed: " . $e;
return;
}
Step 5: Publish a message
Publish a message to the topic.
$messageBody = "test";
$request = new PublishMessageRequest(base64_encode($messageBody));
try {
$res = $topic->publishMessage($request);
echo "MessagePublished! \n";
} catch (MnsException $e) {
// The message may fail to be published if a network error occurs. You can call the CatchException operation to identify and resolve the issue.
echo "PublishMessage Failed: " . $e;
return;
}
Step 6: Receive and delete the message from the queue
After the message is pushed from the topic to the queue, you can extract and delete the message from the queue.
try {
// Call the receiveMessage function to extract the message.
// If you set the waitSeconds parameter to a non-zero value, the request to extract messages is an HTTP long polling request. A response is returned only if the message is sent to the queue or the request times out. The maximum value of the waitSeconds parameter is 30.
$res = $queue->receiveMessage(3);
echo "Receive Message success, MessageBody: " . $res->getMessageBody() . "\n";
// Specify custom logic to process messages based on your business requirements.
// If the program fails or freezes, the message can be consumed by other processes after a period that is specified by the VisibilityTimeout parameter elapses. This prevents the message from being lost.
// Obtain the value of the ReceiptHandle parameter. The receipt handle of the message has a validity period and can be used to modify or delete the message. For more information, see QueueMessage.
$receiptHandle = $res->getReceiptHandle();
// After the message is consumed, you can delete the message from the queue.
$queue->deleteMessage($receiptHandle);
echo "DeleteMessage Succeed! \n";
break;
} catch (MessageNotExistException $e) {
echo "No New Message";
} catch (MnsException $e) {
echo "Process Failed: " . $e;
}
Step 7: Delete the subscription.
Delete the test subscription.
try {
$topic->unsubscribe($subscriptionName);
echo "Unsubscribe Succeed! \n";
} catch (MnsException $e) {
echo "Unsubscribe Failed: " . $e;
return;
}
Step 8: Delete the topic
Delete the test topic.
try {
$this->client->deleteTopic($topicName);
echo "DeleteTopic Succeed! \n";
} catch (MnsException $e) {
echo "DeleteTopic Failed: " . $e;
return;
}
Step 9: Delete the queue
Delete the test queue.
try {
$this->client->deleteQueue($queueName);
echo "DeleteQueue Succeed! \n";
} catch (MnsException $e) {
echo "DeleteQueue Failed: " . $e;
return;
}