This article describes how to use the SDK for Java to create a topic, create a queue, create a subscription, publish a message, receive and delete the message, delete the topic, and delete the queue.

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 use an Alibaba Cloud account, go to the AccessKey Management page of the Alibaba Cloud Management Console to create and view an 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. For more information, see View the endpoints of a topic.
      • 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: Create a queue

You can use the following sample code to create a queue:

public class CreateQueueDemo {

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

        try
        {   
            QueueMeta qMeta = new QueueMeta();
            qMeta.setQueueName("queue-demo");
            qMeta.setPollingWaitSeconds(30);
            CloudQueue cQueue = client.createQueue(qMeta);
            System.out.println("Create queue successfully. URL: " + cQueue.getQueueURL());
        } catch (ClientException ce)
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                    + "Please check your network and DNS availability.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            if (se.getErrorCode().equals("QueueNotExist"))
            {
                System.out.println("Queue is not exist. Please create before use");
            } else if (se.getErrorCode().equals("TimeExpired"))
            {
                System.out.println("The request is time expired. Please check your local machine timeclock");
            }
            se.printStackTrace();
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!");
            e.printStackTrace();
        }

        client.close();
    }

}

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) {
        String region = "";
        String accountId = "";
        String queueName = "TestQueue";
        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("QueueEndpoint2");
            subMeta.setEndpoint(String.format("acs:mns:%s:%s:queues/%s", region, accountId, queueName));
            subMeta.setNotifyContentFormat(SubscriptionMeta.NotifyContentFormat.XML);
            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 a subscription, you can publish messages 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: Receive and delete the message from the queue

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

public class ConsumerDemo {

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

        try{
            CloudQueue queue = client.getQueueRef("queue-demo");
            for (int i = 0; i < 10; i++)
            {
                Message popMsg = queue.popMessage();
                if (popMsg != null){
                    System.out.println("message handle: " + popMsg.getReceiptHandle());
                    System.out.println("message body: " + popMsg.getMessageBodyAsString());
                    System.out.println("message id: " + popMsg.getMessageId());
                    System.out.println("message dequeue count:" + popMsg.getDequeueCount());

                    queue.deleteMessage(popMsg.getReceiptHandle());
                    System.out.println("delete message successfully.\n");
                }
            }
        } catch (ClientException ce)
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                    + "Please check your network and DNS availability.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            if (se.getErrorCode().equals("QueueNotExist"))
            {
                System.out.println("Queue is not exist. Please create queue before use");
            } else if (se.getErrorCode().equals("TimeExpired"))
            {
                System.out.println("The request is time expired. Please check your local machine timeclock");
            }

            se.printStackTrace();
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!");
            e.printStackTrace();
        }

        client.close();
    }
}

Step 7: 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(
                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();
    }
}        

Step 8: Delete the queue

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

public class DeleteQueueDemo {

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

        try
        {
            CloudQueue queue = client.getQueueRef("queue-demo");
            queue.delete();
            System.out.println("Delete cloud-queue-demo successfully!");
        } catch (ClientException ce)
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                    + "Please check your network and DNS availability.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            if (se.getErrorCode().equals("QueueNotExist"))
            {
                System.out.println("Queue is not exist. Please create before use");
            } else if (se.getErrorCode().equals("TimeExpired"))
            {
                System.out.println("The request is time expired. Please check your local machine timeclock");
            }
            se.printStackTrace();
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!");
            e.printStackTrace();
        }

        client.close();
    }

}

Sample code of using tags

You can use the following sample code 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();

        // 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);
    }
}