Todos os produtos
Search
Central de documentação

:Gerenciar filas

Última atualização: Jul 04, 2026

Este tópico descreve como usar o SDK for PHP para criar uma fila, enviar uma mensagem, receber e excluir a mensagem e excluir a fila.

Etapa 1: Preparar o ambiente

  1. Baixe o arquivo CreateQueueAndSendMessage.php.

  2. Abra o arquivo CreateQueueAndSendMessage.php e especifique o AccessKey ID, o AccessKey secret e o endpoint no final do arquivo.

    • AccessKey ID e AccessKey secret

      • Par de AccessKeys usado para chamar operações de API na Alibaba Cloud.

      • Se você usa uma conta da Alibaba Cloud, acesse a página AccessKey Management no Alibaba Cloud Management Console para criar e visualizar seu par de AccessKeys.

      • Se você é um usuário do Resource Access Management (RAM), faça login no RAM console para visualizar seu par de AccessKeys.

    • Endpoint

      • Endpoint usado para acessar o Message Service (Simple Message Queue (formerly MNS)). Para visualizar os endpoints do MNS, faça login no MNS console. Para mais informações, consulte Obter endpoints.

      • Os endpoints do MNS variam conforme a região.

  3. Use o código a seguir, incluído no arquivo CreateQueueAndSendMessage.php, para configurar o SDK:

    // Include an SDK autoload file. 
    require __DIR__ . '/vendor/autoload.php';
    
    // Declare required PHP classes. 
    use AliyunMNS\Client;
    use AliyunMNS\Requests\SendMessageRequest;
    use AliyunMNS\Requests\CreateQueueRequest;
    use AliyunMNS\Exception\MnsException;
  4. Etapa 2: Criar uma fila

    Se não houver nenhuma fila disponível, crie uma. O nome padrão da nova fila é CreateQueueAndSendMessageExample, mas você pode especificar outro nome.

    // 1.Initialize a client. 
    $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);
    
    // 2.Generate a request to create a queue. You can specify the parameters of the queue. 
    // For more information about the parameters of the queue, see Queue. 
    $request = new CreateQueueRequest($queueName);
    try
    {
            $res = $this->client->createQueue($request);
            // 3.The queue is created. 
            echo "QueueCreated! \n";
    }
    catch (MnsException $e)
    {
            // 4.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 failure. 
             echo "CreateQueueFailed: " . $e;
             return;
    }            

    Etapa 3: Enviar uma mensagem

    Após criar a fila, envie uma mensagem para ela.

    // 1.Retrieve the queue. 
    // By default, the SDK for PHP performs Base64 encoding for sent messages and performs Base64 decoding for received messages. 
    // If you do not want the SDK to perform the preceding operations, you can set the Base64 parameter to FALSE when you call the getQueueRef() method: $queue = $this->client->getQueueRef($queueName, FALSE).
    $queue = $this->client->getQueueRef($queueName);
    
    $messageBody = "test";
    // 2.Generate a request to send a message. 
    // You can specify the DelaySeconds and Priority parameters of the message. 
    // For more information about the parameters of the message, see QueueMessage. 
    $bodyMD5 = md5(base64_encode($messageBody));
    $request = new SendMessageRequest($messageBody);
    try
    {
            $res = $queue->sendMessage($request)
            // 3.The message is sent. 
            echo "MessageSent! \n";
    }
    catch (MnsException $e)
    {
            // 4.The message may fail to be sent if a network error occurs or the message is oversized. You can query the cause and solve the problem. 
            echo "SendMessage Failed: " . $e;
            return;
    }            

    Etapa 4: Receber e excluir a mensagem

    Depois de enviar a mensagem, receba-a da fila.

    O parâmetro NextVisibleTime é fundamental para mensagens no Simple Message Queue (formerly MNS). Para mais detalhes, consulte QueueMessage.

    $receiptHandle = NULL;
    try
    {
            // 1.Call the receiveMessage() function. 
            // We recommend that you set the WaitSeconds parameter to 30 when you call the receiveMessage() function. 
            // If you set the WaitSeconds parameter to a non-zero value, the request of receiving 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(30);
            echo "ReceiveMessage Succeed! \n";
            if (strtoupper($bodyMD5) == $res->getMessageBodyMD5())
            {
                 echo "You got the message sent by yourself! \n";
            }
            // 2.Retrieve 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();
    }
    catch (MnsException $e)
    {
            // 3.The message may fail to be received if an error occurs. You can query the cause and solve the problem. 
            echo "ReceiveMessage Failed: " . $e;
            return;
    }
    
    // Specify your own logic to process messages based on your business requirements. 
    // The VisibilityTimeout parameter specifies the period when a message remains inactive in the queue after being consumed by a client. After the specified period, the message becomes active again and can be consumed by other clients. The message is not lost if the program fails or is stuck. 
    
    // 4.After the message is consumed, you can delete the message from the queue. 
    try
    {
            // 5.Call the deleteMessage() function. 
            $res = $queue->deleteMessage($receiptHandle);
            echo "DeleteMessage Succeed! \n";
    }
    catch (MnsException $e)
    {
            // 6.If an error occurs, you can call the CatchException operation to identify and resolve the failure. 
            // If the receipt handle expires, the MessageNotExist error is returned. This error indicates that you cannot use the receipt handle to find the corresponding message. 
            // To ensure that you can consume the message before the receipt handle expires, you must set the VisibilityTimeout parameter to an appropriate value. You can call the changeMessageVisibility() function to modify the value of the VisibilityTimeout parameter. 
            echo "DeleteMessage Failed: " . $e;
            return;
    }            

    Etapa 5: Excluir a fila

    Use o código de exemplo a seguir para excluir a fila:

    try {
            $this->client->deleteQueue($queueName);
            echo "DeleteQueue Succeed! \n";
    } catch (MnsException $e) {
            echo "DeleteQueue Failed: " . $e;
            return;
    }