This topic describes how to use the sample code in the Python SDK to create a queue, send a message, receive and delete the messages, and delete the queue.

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 queue

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

public class CreateQueueDemo {
    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 queueName = "TestQueue";
        QueueMeta meta = new QueueMeta (); //Specify the parameters of the queue. For more information about the parameters, visit https://www.alibabacloud.com/help/zh/doc-detail/27476.htm.
        meta.setQueueName(queueName);  //Specify a queue name.
        meta.setPollingWaitSeconds(15);
        meta.setMaxMessageSize(2048L);

        try {
            CloudQueue queue = client.createQueue(meta);
        } catch (ClientException ce)
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                   + "Please check your network and DNS availablity.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            se.printStackTrace();
            logger.error("MNS exception requestId:" + se.getRequestId(), se);
            if (se.getErrorCode() ! = null) {
                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");
                }
            /*
            you can get more MNS service error code from following link:
            https://www.alibabacloud.com/help/doc-detail/27501.htm
            */
            }
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!") ;
            e.printStackTrace();
        }

        client.close();  //Use the close() method of MNSClient to release the resources.
    }
}

Step 3: Send a message

After creating a queue, you can send messages to the queue.

public class ProducerDemo {
    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.

        try {
            CloudQueue queue = client.getQueueRef("TestQueue");
            Message message = new Message();
            message.setMessageBody("I am test message ");
            Message putMsg = queue.putMessage(message);
            System.out.println("Send message id is: " + putMsg.getMessageId());
        } catch (ClientException ce)
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                   + "Please check your network and DNS availablity.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            se.printStackTrace();
            logger.error("MNS exception requestId:" + se.getRequestId(), se);
            if (se.getErrorCode() ! = null) {
                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");
                }
            /*
            you can get more MNS service error code from following link:
            https://www.alibabacloud.com/help/doc-detail/27501.htm
            */
            }
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!") ;
            e.printStackTrace();
        }

        client.close();  //Use the close() method of MNSClient to release the resources.
    }
}

Step 4: Receive and delete the message

A message has been sent to the queue. You can use the following sample code to receive and delete the message.

public class ConsumerDemo {
    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.

        try{
            CloudQueue queue = client.getQueueRef("TestQueue");
            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());

                //Delete the message that has been received.
                 queue.deleteMessage(popMsg.getReceiptHandle());
                    System.out.println("delete message successfully.\n");
            }
            else{
                System.out.println("message not exist in TestQueue.\n");
            }
        } catch (ClientException ce)
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                    + "Please check your network and DNS availablity.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            se.printStackTrace();
            logger.error("MNS exception requestId:" + se.getRequestId(), se);
            if (se.getErrorCode() ! = null) {
                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");
                }
            /*
            you can get more MNS service error code from following link:
            https://www.alibabacloud.com/help/doc-detail/27501.htm
            */
            }
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!") ;
            e.printStackTrace();
        }

        client.close();
    }
}

Step 5: Delete an application

public class DeleteQueueDemo {
    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.

        try{
            CloudQueue queue = client.getQueueRef("TestQueue");
            queue.delete();
        } catch (ClientException ce)
        {
            System.out.println("Something wrong with the network connection between client and MNS service."
                    + "Please check your network and DNS availablity.");
            ce.printStackTrace();
        } catch (ServiceException se)
        {
            se.printStackTrace();
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!") ;
            e.printStackTrace();
        }

        client.close();
    }
}