This topic describes how to use the SDK for Java to create a queue, send a message, receive and delete the message, 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 configure the endpoint, AccessKey ID, and AccessKey secret in the file.
    Note The home directory on Linux is /home/YOURNAME/. The home directory on Windows 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 Message Service (MNS). To view the endpoint of MNS, log on to the MNS console, and click Get Endpoint in the upper-right corner.
      • The endpoint of MNS varies based on different regions. You can use Internet endpoints and internal endpoints based on your business requirements.

Step 2: 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("YourAccessId", "YourAccessKey", "MNSEndpoint");
        MNSClient client = account.getMNSClient(); // The CloudAccount or MNSClient class provides 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, see Queue.

        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");
                }
            // For more information about error codes, see Error codes.
            }
        } 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 the queue is created, you can use the following sample code to send a message 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 provides 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");
                }
             // For more information about error codes, see Error codes.
            }
        } 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

After the message is 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 provides 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 received message.
                 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");
                }
             // For more information about error codes, see Error codes.
            }
        } catch (Exception e)
        {
            System.out.println("Unknown exception happened!") ;
            e.printStackTrace();
        }

        client.close();
    }
}

Step 5: Delete the queue

Deletes the queue that is created in Step 2.

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