Topic user guide

更新时间:
复制 MD 格式

This topic describes how to use the sample code in the C# SDK to create topics, queues, and subscriptions, and to publish messages.

Step 1: Preparations

  1. Download the latest C# SDK. Unzip the package and import the project into Visual Studio.

  2. In the four projects, find the SDK project AliyunSDK_MNS. Right-click the project name and select Rebuild. This generates the Aliyun.MNS.dll file in the bin directory.

    Note

    The other projects must reference Aliyun.MNS.dll. Configure the references for these projects.

  3. Configure the AliyunSDK_MNS_Sample project.

    1. Set the AliyunSDK_MNS_Sample project as the startup project, and set SyncTopicOperations.cs as the startup object.

    2. Open the SyncTopicOperations.cs file and configure the following items:

      • AccessKey ID and AccessKey secret

      • Endpoint

        • This is the endpoint used to access Simple Message Queue (formerly MNS). To view the endpoint, log on to the SMQ console. For more information, see Obtain an endpoint.

        • Endpoints vary by region.

Step 2: Create a topic

If you have not created a topic, you must first create one. The default topic name is TestCSharpTopic. You can also modify the code to specify a different topic name.

// 1. Create a CreateTopicRequest instance and pass topicName as a parameter. You can also pass TopicAttributes to set custom topic properties when you create the topic.
var createTopicRequest = new CreateTopicRequest
{
    TopicName = _topicName
};

Topic topic = null;
try
{
    topic = client.CreateTopic(createTopicRequest);
    Console.WriteLine("Create topic successfully, topic name: {0}", topic.TopicName);
}
catch (MNSException me)
{
    // 2. The CreateTopic operation may fail due to network errors or because the topic already exists. Catch the exception and handle the error. You can also catch specific exceptions, such as TopicAlreadyExistException, for separate processing.
    Console.WriteLine("CreateTopic Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Create topic failed, exception info: " + ex.Message);
    return;
}          

Step 3: Create a queue

If you have not created a queue, you must first create one. The default queue name is myqueue. You can modify the code to specify a different queue name.

// 1. Specify the properties for the queue. For more information about queue properties, see Queue.
var createQueueRequest = new CreateQueueRequest
{
    QueueName = _queueName,
    Attributes =
    {
        // VisibilityTimeout is the most important property. The default value is 30 seconds.
        VisibilityTimeout = 30,
        MaximumMessageSize = 40960,
        MessageRetentionPeriod = 345600,
        // PollingWaitSeconds is the timeout period for long polling.
        PollingWaitSeconds = 30
    }
};

try
{
    // 2. Create the queue. If you do not need to specify queue properties, you can call client.CreateQueue(_queueName).
    var queue = client.CreateQueue(createQueueRequest);
    Console.WriteLine("Create queue successfully, queue name: {0}", queue.QueueName);
}
catch (MNSException me)
{
    // 3. If an error occurs when you create the queue, you can handle the error based on the error code. You can also catch exceptions such as QueueAlreadyExistException to handle them separately.
    Console.WriteLine("CreateQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Create queue failed, exception info: " + ex.Message);
}           

Step 4: Create a subscription

Subscribe to the created topic.

string region = "";
string accountId = "";
string queueName = "TestQueue";
try
{
    // 1. Generate SubscriptionAttributes. The second parameter is the endpoint of the subscription.
    SubscribeResponse res = topic.Subscribe(_subscriptionName, "acs:mns:" + region +":" + accountId +":queues/" + queueName);
    // 2. The subscription is created.
    Console.WriteLine("Subscribe succeed");
}
catch (MNSException me)
{
    // 3. The subscription may fail due to network errors or because a subscription with the same name already exists. Catch the exception and handle the error.
    Console.WriteLine("Subscribe Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Subscribe failed, exception info: " + ex.Message);
}                       

Step 5: Publish a message

Publish a message to the topic.

try
{
    var response = topic.PublishMessage("message here </asdas\">");
    // 1. The message is published.
    Console.WriteLine("PublishMessage succeed! " + response.MessageId);
}
catch (MNSException me)
{
    // 2. The PublishMessage operation may fail due to network errors. Catch the exception and handle the error.
    Console.WriteLine("PublishMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("PublishMessage failed, exception info: " + ex.Message);
}           

Step 6: Receive and delete a message from the queue

After a message is pushed from a topic to a queue, receive and delete the message from the queue.

try
{
    // 1. Call the receiveMessage function.
    // The receiveMessage function accepts the waitSeconds parameter. Set this parameter to 30.
    // A waitSeconds value other than 0 indicates that this receiveMessage call is an HTTP long polling request. If no message exists in the queue, the request waits on the server until a message is available. The maximum wait time is the value of waitSeconds, up to a maximum of 30.
    var receiveMessageResponse = nativeQueue.ReceiveMessage(30);
    // 2. Get the receipt handle. This is a time-sensitive handle that you can use to set message properties and delete the message. For more information, see QueueMessage.
    _receiptHandle = message.ReceiptHandle;
}
catch (MNSException me)
{
    // 3. Similar to CreateQueue and SendMessage, an error can occur when you call ReceiveMessage. Catch the exception and handle it.
    Console.WriteLine("ReceiveMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("ReceiveMessage failed, exception info: " + ex.Message);
}

// Add your logic to process the message here. This step is omitted in the sample.
// If an exception such as a program crash or freeze occurs, the message becomes visible again after the VisibilityTimeout period expires. This allows other processes to handle the message and prevents message loss.

// 4. After the message is processed, delete it from the queue.
try
{
    // 5. Call deleteMessage.
    var deleteMessageResponse = nativeQueue.DeleteMessage(_receiptHandle);
}
catch (MNSException me)
{
    // 6. Catch the exception and handle it.
    // If the receipt handle has expired, the error code is MessageNotExist. This indicates that the message cannot be found using this receipt handle.
    // To prevent the receipt handle from expiring, make sure that the VisibilityTimeout value is long enough for the message to be processed. During message processing, you can also call the changeMessageVisibility function to extend the VisibilityTimeout period of the message.
    Console.WriteLine("DeleteMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Delete message failed, exception info: " + ex.Message);
}            

Step 7: Delete the topic

Delete the test topic.

try
{
    client.DeleteTopic(_topicName);
    Console.WriteLine("Delete topic succeed");
}
catch (Exception ex)
{
    Console.WriteLine("Delete topic failed, exception info: " + ex.Message);
}            

Step 8: Delete the queue

Delete the test 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);
}