Topic operations

Last Updated: Mar 27, 2017

This document introduces how to use sample code in Java SDK of MNS, including CreateTopic,CreateSubscription,Publish Message,ReceiveMessage and DeleteTopic.

1. Preparation

  1. Download the latest version of Java sdk and unzip to aliyun-sdk-mns-samples folder.
  2. Import the maven project under folder: aliyun-sdk-mns-samples.
  3. Create config file with the endpoint, AccessKeyID, AccessKeySecret under the user folder(/home/YOURNAME/).
  4. Config file sample:
    1. mns.accountendpoint=http://$accountid.mns.$region.aliyuncs.com
    2. mns.accesskeyid=$your_accesskeyid
    3. mns.accesskeysecret=$your_accesskeysecret
    Notes:
    • AK is the short name for $your_accesskeyid and $your_accesskeysecret, which are used for accessing Alibaba Cloud Service in config file above. AK can be fetched from following AccessKey Website while using main account or from Alibaba Cloud RAM Console while using sub-account.
    • mns.accountendpoint is the access point for Alibaba Cloud Message Service. It can be acquired from Message Service Console by clicking the button Get Endpoint on the top right corner.

2. Create a topic

To create a topic as sample code below shows.

  1. public class CreateTopicDemo {
  2. public static void main(String[] args) {
  3. CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
  4. MNSClient client = account.getMNSClient(); // It's suggested to use sigleton mode in the application code for both CloudAccount and MNSClient are thread safe.
  5. String topicName = "TestTopic";
  6. TopicMeta meta = new TopicMeta();
  7. meta.setTopicName(topicName);
  8. try {
  9. CloudTopic topic = client.createTopic(meta);
  10. } catch (Exception e)
  11. e.printStackTrace();
  12. System.out.println("create topic error, " + e.getMessage());
  13. }
  14. client.close();
  15. }
  16. }

3. Start a HttpEndpoint

There is a sample code file HttpEndpoint.java under folder aliyun-sdk-mns-samples in which lies a local http message receiver including following functions:

  1. Verify signature of the push request from MNS
  2. Parse the body to push request
  3. Response the return code 200 for the push request

For the implementation of source code on HttpEndpoint, refer to the source code in SDK. There is a sample code file “HttpEndpoint.java” in folder: src/main/java/com/aliyun/mns/sample of Java SDK.

4. Create a subscription

Endpoint, Retry policy, message format should be set when creating subscription.

  1. public class SubscribeDemo {
  2. public static void main(String[] args) {
  3. CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
  4. MNSClient client = account.getMNSClient();
  5. CloudTopic topic = client.getTopicRef("TestTopic");
  6. try {
  7. SubscriptionMeta subMeta = new SubscriptionMeta();
  8. subMeta.setSubscriptionName("TestSub");
  9. subMeta.setEndpoint(HttpEndpoint.GenEndpointLocal());
  10. subMeta.setNotifyContentFormat(SubscriptionMeta.NotifyContentFormat.XML);
  11. //subMeta.setFilterTag("filterTag"); //Set filterTag for subscription
  12. String subUrl = topic.subscribe(subMeta);
  13. System.out.println("subscription url: " + subUrl);
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. System.out.println("subscribe/unsubribe error");
  17. }
  18. client.close();
  19. }
  20. }

5. Publish a message

To publish message to the topic after the creation of topic and subscription.

  1. public class PublishMessageDemo {
  2. public static void main(String[] args) {
  3. CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
  4. MNSClient client = account.getMNSClient();
  5. CloudTopic topic = client.getTopicRef("TestTopic");
  6. try {
  7. TopicMessage msg = new Base64TopicMessage();
  8. msg.setMessageBody("hello world!");
  9. //msg.setMessageTag("filterTag"); //Set filterTag filterTag
  10. msg = topic.publishMessage(msg);
  11. System.out.println(msg.getMessageId());
  12. System.out.println(msg.getMessageBodyMD5());
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. System.out.println("subscribe error");
  16. }
  17. client.close();
  18. }
  19. }

6. Check the message in http endpoint

Message service will push the message published in step 5 to the endpoint.

7. Cancel the subscription

Cancel the subscription if you do not want to receive the message from topic.

  1. public class UnsubscribeDemo {
  2. public static void main(String[] args) {
  3. CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
  4. MNSClient client = account.getMNSClient();
  5. CloudTopic topic = client.getTopicRef("TestTopic");
  6. try {
  7. topic.unsubscribe("TestSub");
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. System.out.println("unsubribe error");
  11. }
  12. client.close();
  13. }
  14. }

8. Delete a topic

  1. public class DeleteTopicDemo {
  2. public static void main(String[] args) {
  3. CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
  4. MNSClient client = account.getMNSClient();
  5. CloudTopic topic = client.getTopicRef("TestTopic");
  6. try {
  7. topic.delete();
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. System.out.println("delete topic error");
  11. }
  12. client.close();
  13. }
  14. }

9. Sample for using FilterTag(An End2End Case)

  1. package com.aliyun.mns.samples;
  2. import com.aliyun.mns.client.CloudAccount;
  3. import com.aliyun.mns.client.CloudQueue;
  4. import com.aliyun.mns.client.CloudTopic;
  5. import com.aliyun.mns.client.MNSClient;
  6. import com.aliyun.mns.common.utils.ServiceSettings;
  7. import com.aliyun.mns.model.*;
  8. public class TopicSample {
  9. public static void main(String[] args) {
  10. CloudAccount account = new CloudAccount(
  11. ServiceSettings.getMNSAccessKeyId(),
  12. ServiceSettings.getMNSAccessKeySecret(),
  13. ServiceSettings.getMNSAccountEndpoint());
  14. MNSClient client = account.getMNSClient();
  15. // step 1 : Create Queue
  16. QueueMeta queueMeta = new QueueMeta();
  17. queueMeta.setQueueName("TestSubForQueue");
  18. CloudQueue queue = client.createQueue(queueMeta);
  19. // step 2 : Create Topic
  20. TopicMeta topicMeta = new TopicMeta();
  21. topicMeta.setTopicName("TestTopic");
  22. CloudTopic topic = client.createTopic(topicMeta);
  23. // step 3 : Create Subscription(subcribes message to queue created in step 1)
  24. SubscriptionMeta subMeta = new SubscriptionMeta();
  25. subMeta.setSubscriptionName("TestForQueueSub");
  26. subMeta.setNotifyContentFormat(SubscriptionMeta.NotifyContentFormat.SIMPLIFIED);
  27. subMeta.setEndpoint(topic.generateQueueEndpoint("TestSubForQueue"));
  28. subMeta.setFilterTag("filterTag");
  29. topic.subscribe(subMeta);
  30. // step 4 : Public Message
  31. TopicMessage msg = new Base64TopicMessage();
  32. msg.setMessageBody("hello world");
  33. msg.setMessageTag("filterTag");
  34. msg = topic.publishMessage(msg);
  35. // step 5 : Get Message from queue
  36. Message msgReceive = queue.popMessage(30);
  37. System.out.println("ReceiveMessage From TestSubForQueue:");
  38. System.out.println(msgReceive.getMessageBody());
  39. System.exit(0);
  40. }
  41. }
Thank you! We've received your feedback.