This topic describes how to use the sample code in the Java SDK to create a topic, create a subscription, publish a message, receive the message, and delete the topic.

Step 1: Prepare the environment

  1. Download the latest version of the Java SDK, and extract the package to the aliyun-sdk-mns-samples folder.
  2. Import a Maven project into Eclipse and select the aliyun-sdk-mns-samples folder.
  3. In the home directory (/home/YOURNAME/ on Linux or C:\Users\YOURNAME on Windows), create an .aliyun-mns.properties file and configure the endpoint, AccessKey ID, and AccessKey secret in the file.
    • AccessKey ID and AccessKey secret
      • The AccessKey pair that is used to access the Alibaba Cloud API.
      • If you are using an Alibaba Cloud account, go to the Security Management page of the Alibaba Cloud console to create and view AccessKey pairs.
      • If you are a RAM user, log on to Alibaba Cloud RAM console to view AccessKey pairs.
    • Endpoint
      • The endpoint that is used to access MNS. Log on to the MNS console, and click Get Endpoint in the upper-right corner to view endpoints.
      • Endpoints vary based on regions. You can also use Internet endpoints and intranet endpoints based on your needs.

Step 2: Create a topic

You can use the following sample code to create a topic. For more information about the parameters of a topic, see Topic.

public class CreateTopicDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
        MNSClient client = account.getMNSClient(); //The CloudAccount or MNSClient class has only one instance in the program to ensure thread safety.

        String topicName = "TestTopic";
        TopicMeta meta = new TopicMeta();
        meta.setTopicName(topicName);

        try {
            CloudTopic topic = client.createTopic(meta);
        } catch (Exception e)
            e.printStackTrace();
            System.out.println("create topic error, " + e.getMessage());
        }

        client.close();
    }
}         

Step 3: Enable an HTTP endpoint

aliyun-sdk-mns-samples provides the HttpEndpoint.java class, which allows you to enable an on-premises HTTP endpoint to receive messages. The HTTP endpoint performs the following operations:
  • Signs the request that is sent from MNS for verification.
  • Parses the message content.
  • Returns HTTP status code 200.

For more information about the sample code, see the SDK.

Step 4: Create a subscription

Create a subscription to the topic. You must specify the Endpoint, Notification Strategy, and Notification Content Format parameters based on your needs. Currently, endpoints support HTTP URLs, email addresses, queues, mobile numbers, and Alibaba Cloud SMS.

public class SubscribeDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
        MNSClient client = account.getMNSClient(); //The CloudAccount or MNSClient class has only one instance in the program to ensure thread safety.

        CloudTopic topic = client.getTopicRef("TestTopic");
        try {
            SubscriptionMeta subMeta = new SubscriptionMeta();
            subMeta.setSubscriptionName("TestSub");
            subMeta.setEndpoint(HttpEndpoint.GenEndpointLocal());
            subMeta.setNotifyContentFormat(SubscriptionMeta.NotifyContentFormat.XML);
            //subMeta.setFilterTag("filterTag"); //Configure a tag that is used to filter messages.
            String subUrl = topic.subscribe(subMeta);
            System.out.println("subscription url: " + subUrl);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("subscribe/unsubribe error");
        }

        client.close();
    }
}      

Step 5: Publish a message

After creating a topic and subscription, and starting the HTTP server, you can publish messages to the topic.

public class PublishMessageDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
        MNSClient client = account.getMNSClient(); //The CloudAccount or MNSClient class has only one instance in the program to ensure thread safety.

        CloudTopic topic = client.getTopicRef("TestTopic");
        try {
            TopicMessage msg = new Base64TopicMessage(); //You can specify whether to perform Base64 encoding on topic messages.
            msg.setMessageBody("hello world!") ;
            //msg.setMessageTag("filterTag"); //Configure a tag for the message.
            msg = topic.publishMessage(msg);
            System.out.println(msg.getMessageId());
            System.out.println(msg.getMessageBodyMD5());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("subscribe error");
        }

        client.close();
    }
}          

Step 6: View the received message on the HTTP server

In Step 5, a message is published to the topic, and MNS automatically pushes the message to the HTTP endpoint. The message is printed on the HTTP server.

Step 7: Delete the subscription

If you do not need to receive messages from the topic, you can delete the subscription.

public class UnsubscribeDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
        MNSClient client = account.getMNSClient(); //The CloudAccount or MNSClient class has only one instance in the program to ensure thread safety.

        CloudTopic topic = client.getTopicRef("TestTopic");
        try {
            topic.unsubscribe("TestSub");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("unsubribe error");
        }

        client.close();
    }
}            

Step 8: Delete the topic

You can use the following sample code to delete the topic.

public class DeleteTopicDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount("YourAccessId", "YourAccessKey", "MNSEndpoint");
        MNSClient client = account.getMNSClient(); //The CloudAccount or MNSClient class has only one instance in the program to ensure thread safety.

        CloudTopic topic = client.getTopicRef("TestTopic");
        try {
            topic.delete();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("delete topic error");
        }

        client.close();
    }
}          

Sample code of using tags to filter messages

package com.aliyun.mns.samples;


import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.utils.ServiceSettings;
import com.aliyun.mns.model.*;

public class TopicSample {

    public static void main(String[] args) {
        CloudAccount account = new CloudAccount(
                ServiceSettings.getMNSAccessKeyId(),
                ServiceSettings.getMNSAccessKeySecret(),
                ServiceSettings.getMNSAccountEndpoint());
        MNSClient client = account.getMNSClient();

        //Step 1: Create a queue.
        QueueMeta queueMeta = new QueueMeta();
        queueMeta.setQueueName("TestSubForQueue");
        CloudQueue queue = client.createQueue(queueMeta);
        //Step 2: Create a topic.
        TopicMeta topicMeta = new TopicMeta();
        topicMeta.setTopicName("TestTopic");
        CloudTopic topic = client.createTopic(topicMeta);
        //Step 3: Create a subscription.
        SubscriptionMeta subMeta = new SubscriptionMeta();
        subMeta.setSubscriptionName("TestForQueueSub");
        subMeta.setNotifyContentFormat(SubscriptionMeta.NotifyContentFormat.SIMPLIFIED);
        subMeta.setEndpoint(topic.generateQueueEndpoint("TestSubForQueue"));
        subMeta.setFilterTag("filterTag");
        topic.subscribe(subMeta);
        //Step 4: Publish a message.
        TopicMessage msg = new Base64TopicMessage();
        msg.setMessageBody("hello world");
        msg.setMessageTag("filterTag");
        msg = topic.publishMessage(msg);
        //Step 5: Retrieve the message from the queue that is specified in the subscription.
        Message msgReceive = queue.popMessage(30);
        System.out.println("ReceiveMessage From TestSubForQueue:");
        System.out.println(msgReceive.getMessageBody());
        System.exit(0);
    }
}