This article describes how to use MNS SDK for Java 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 SDK for Java, and decompress 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, create a file named .aliyun-mns.properties and specify the endpoint, AccessKey ID, and AccessKey secret in the file.
    Note In Linux, the home directory is /home/YOURNAME/. In Windows, the home directory is C:\Users\YOURNAME.
    • 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 MNS. To view the endpoint, log on to the MNS console, and click Get Endpoint in the upper-right corner.
      • The endpoint of MNS varies depending on the region. You can use Internet endpoints and internal endpoints based on your business requirements.

Step 2: Create a topic

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

public class CreateTopicDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount(
                ServiceSettings.getMNSAccessKeyId(),
                ServiceSettings.getMNSAccessKeySecret(),
                ServiceSettings.getMNSAccountEndpoint());
        MNSClient client = account.getMNSClient(); // The CloudAccount or MNSClient class provides only one instance in the program to ensure thread security. 

        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 that allows you to enable an on-premises HTTP endpoint to receive messages.
  • Signs the request that is sent from MNS for verification.
  • Parses the message body.
  • Returns HTTP status code 200.

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

Step 4: Create a subscription

After the topic is created, you can create a subscription to the topic. You must specify the Endpoint, Notification Strategy, and Notification Content Format parameters based on your business requirements. You can specify HTTP URLs, email addresses, MNS queues, iOS or Android applications, or mobile numbers for the Endpoint parameter.

public class SubscribeDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount(
                ServiceSettings.getMNSAccessKeyId(),
                ServiceSettings.getMNSAccessKeySecret(),
                ServiceSettings.getMNSAccountEndpoint());
        MNSClient client = account.getMNSClient(); // The CloudAccount or MNSClient class provides only one instance in the program to ensure thread security. 

        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 you create a topic and subscription and enable the HTTP endpoint, you can publish a message to the topic.

public class PublishMessageDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount(
                ServiceSettings.getMNSAccessKeyId(),
                ServiceSettings.getMNSAccessKeySecret(),
                ServiceSettings.getMNSAccountEndpoint());
        MNSClient client = account.getMNSClient(); // The CloudAccount or MNSClient class provides only one instance in the program to ensure thread security. 

        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"); // Specify 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 messages on the HTTP server

  1. In Step 5, a message is published to the topic, and MNS pushes the message to the HTTP endpoint.
  2. The HTTP endpoint indicates whether the message is received in the MNS console.

Step 7: Delete the subscription

If you no longer 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(
                ServiceSettings.getMNSAccessKeyId(),
                ServiceSettings.getMNSAccessKeySecret(),
                ServiceSettings.getMNSAccountEndpoint());
        MNSClient client = account.getMNSClient(); // The CloudAccount or MNSClient class provides only one instance in the program to ensure thread security. 

        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

Delete the test topic.

public class DeleteTopicDemo {
    public static void main(String[] args) {
        CloudAccount account = new CloudAccount(
                ServiceSettings.getMNSAccessKeyId(),
                ServiceSettings.getMNSAccessKeySecret(),
                ServiceSettings.getMNSAccountEndpoint());
        MNSClient client = account.getMNSClient(); // The CloudAccount or MNSClient class provides only one instance in the program to ensure thread security. 

        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 a filter tag

Sample code:

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();

        // 1. Create a queue. 
        QueueMeta queueMeta = new QueueMeta();
        queueMeta.setQueueName("TestSubForQueue");
        CloudQueue queue = client.createQueue(queueMeta);
        // 2. Create a topic. 
        TopicMeta topicMeta = new TopicMeta();
        topicMeta.setTopicName("TestTopic");
        CloudTopic topic = client.createTopic(topicMeta);
        // 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);
        // 4. Publish a message. 
        TopicMessage msg = new Base64TopicMessage();
        msg.setMessageBody("hello world");
        msg.setMessageTag("filterTag");
        msg = topic.publishMessage(msg);
        // 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);
    }
}