All Products
Search
Document Center

Simple Message Queue (formerly MNS):Manage queues

最終更新日:Sep 02, 2024

This article describes how to use the SDK for PHP to create a queue, send a message, receive and delete the message, and delete the queue.

Step 1: Prepare the environment

  1. Download the latest version of the SDK for C#, decompress the package, and then add the folder to Visual Studio as a solution.

  2. The solution contains four projects. Right-click the AliyunSDK_MNS project and select Rebuild. The Aliyun.MNS.dll file is generated in the bin directory of the project.

    Note

    Specify the Aliyun.MNS.dll file as the reference of other projects.

  3. To view sample code that you can use to manage queues, open the SyncTopicSample.cs file in the AliyunSDK_MNS_Sample project.

    1. Set AliyunSDK_MNS_Sample as the startup project and SyncTopicSample as the startup object.

    2. Open the SyncTopicSample.cs file and specify the AccessKey ID, AccessKey secret, and endpoint at the beginning of the file.

      • AccessKey ID and AccessKey secret

        • The AccessKey pair that is used to call API operations in Alibaba Cloud.

        • If you are using an Alibaba Cloud account, go to the AccessKey Management page of the Alibaba Cloud Management Console to create and view your AccessKey pair.

        • If you are a Resource Access Management (RAM) user, log on to the RAM console to view your AccessKey pair.

      • Endpoint

        • The endpoint that is used to access Simple Message Queue (formerly MNS). To view the endpoints of SMQ, log on to the SMQ console. For more information, see View the endpoints of a queue.

        • The endpoints of SMQ vary based on regions.

Step 2: Create a queue

If no queue is available, you must create a queue. The default name of the new queue is myqueue. You can also specify another queue name.

// 1.You can specify the parameters of the queue based on your needs. For more information about the parameters of a queue, see Queue. 
var createQueueRequest = new CreateQueueRequest
{
    QueueName = _queueName,
    Attributes =
    {
        // You must specify the VisibilityTimeout parameter. Default value: 30. 
        VisibilityTimeout = 30,
        MaximumMessageSize = 40960,
        MessageRetentionPeriod = 345600,
        // The PollingWaitSeconds parameter specifies the timeout period of a long polling request. 
        PollingWaitSeconds = 30
    }
};

try
{
    // 2.Create a queue. If you do not need to specify the parameters of a queue, you can use the client.CreateQueue(_ queueName) method to create a queue. 
    var queue = client.CreateQueue(createQueueRequest);
    Console.WriteLine("Create queue successfully, queue name: {0}", queue.QueueName);
}
catch (MNSException me)
{
    // 3.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. 
    Console.WriteLine("CreateQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Create queue failed, exception info: " + ex.Message);
}           

Step 3: Send a message

After the queue is created, you can send messages to the queue.

try
{
    // 1.Retrieve a queue. 
    var nativeQueue = client.GetNativeQueue(_queueName);
    // 2.Generate a request to send a message. You can specify the parameters of the message based on your needs. 
    var sendMessageRequest = new SendMessageRequest("Alibaba<MessageBody>Cloud");
    // 3.Send a message. If you do not need to specify the parameters of a message, you can use the nativeQueue.SendMessage ("MessageBody") method. 
    var sendMessageResponse = nativeQueue.SendMessage(sendMessageRequest);
    Console.WriteLine("Send message succeed“);
}
catch (MNSException me)
{
    // 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. 
    Console.WriteLine("SendMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Send message failed, exception info: " + ex.Message);
}            

Step 4: Receive and delete the message

If the message exists in a queue, you can receive the message.

You must specify the NextVisibleTime parameter in SMQ. For more information, see QueueMessage.

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, a request of receiving messages is an HTTP long polling request. The long-polling request holds until a message is available in the queue. The maximum value of the WaitSeconds parameter is 30. 
    var receiveMessageResponse = nativeQueue.ReceiveMessage(30);
    // 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 = message.ReceiptHandle;
}
catch (MNSException me)
{
    // 3.A message may fail to be received if an error occurs. You can call the CatchException operation to identify and resolve the failure. 
    Console.WriteLine("ReceiveMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("ReceiveMessage failed, exception info: " + ex.Message);
}

// Specify your own logic to process messages based on your needs. 
// The VisibilityTimeout parameter specifies the period when a message remains in the Inactive state in the queue after the message has been consumed by a client. After the specified period, the message changes to the Active state again and can be consumed by other clients. This prevents message loss against unexpected exits. 

// 4.After a message is consumed, you can delete the message from the queue. 
try
{
    // 5.Call the deleteMessage() function. 
    var deleteMessageResponse = nativeQueue.DeleteMessage(_receiptHandle);
}
catch (MNSException me)
{
    // 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 make sure 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. 
    Console.WriteLine("DeleteMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Delete message failed, exception info: " + ex.Message);
}            

Step 5: Delete the queue

You can use the following sample code to delete the queue:

try 
{
    var deleteQueueResponse = client.DeleteQueue(deleteQueueRequest);
} 
catch (MNSException me)
{
    Console.WriteLine("DeleteQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Delete queue failed, exception info: " + ex.Message);
}