All Products
Search
Document Center

Simple Message Queue (formerly MNS):Use topics

Last Updated:Nov 01, 2024

This topic describes the prerequisites and sample code for processing messages based on topics by using Simple Message Queue (formerly MNS) (SMQ) SDK for PHP.

Prerequisites

  • SMQ SDK for PHP is installed. For more information, see Install SDK for PHP.

  • An endpoint and an access credential are configured. For more information, see Configure endpoints and access credentials.

  • The settings at the beginning of the CreateTopicAndPushMessageToQueue.php file are modified based on the comments.

    // Replace the value with the path of the autoload.php file in the vendor directory downloaded by the composer. 
    require_once __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;

Publish a Base64-encoded message

For more information about how to encode a message body in Base64, see Encode a message body.

For more information about the complete sample code, see CreateTopicAndPushMessageToQueue.php.

// publish base64 encoded message
$messageBody = "test";
$request = new PublishBase64MessageRequest($messageBody);
try {
    $res = $topic->publishMessage($request);
    echo "Base64MessagePublished!  \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 "PublishBase64Message Failed: " . $e;
    return;
}