All Products
Search
Document Center

Simple Message Queue (formerly MNS):Use sample code to send a message to a queue

Last Updated:Oct 28, 2024

This topic describes how to use Simple Message Queue (formerly MNS) (SMQ) SDK for Java to send a message to a queue.

Prerequisites

Authorization information

By default, you can call this operation only with an Alibaba Cloud account. You can call this operation as a Resource Access Management (RAM) user only after you grant the required permissions to the RAM user. The following table describes the authorization information of this operation.

Name

Value

API

SendMessage

Action

mns:SendMessage

Resource

acs:mns:$region:$accountid:/queues/$queueName/messages

Usage notes

  • You can call this operation to send a message to a queue. A standard message is immediately consumed after the message is sent to the queue. If you do not want a message to be immediately consumed after it is sent to a queue, you can specify the DelaySeconds parameter when you send the message. If you set the DelaySeconds parameter to a value that is greater than 0, the initial state of the message is Delayed after the message is sent to a queue. The message cannot be consumed until the period specified by the DelaySeconds parameter ends and the state of the message changes to Active.

  • If the value of the DelaySeconds parameter that is specified for the message is different from the value of the DelaySeconds parameter that is specified for the queue, the value of the DelaySeconds parameter that is specified for the message takes effect.

  • When you call the operation to send a message, we recommend that you encode the message body in Base64 to prevent errors caused by special characters.

  • In this sample code, you can use the endpoint based on your actual environment. If you only want to perform a local test, you can use a public endpoint. If you want to send a message online, we recommend that you use an internal endpoint. For more information about the regions and endpoints that are supported by SMQ, see Regions and endpoints.

Encoding methods for message bodies

If the message body does not contain special characters, we recommend that you do not use Base64 encoding.

  • To send a message, use the message.setMessageBodyAsRawString method to set the message body.

  • To receive a message, use the message.getMessageBodyAsRawString method to obtain the message body.

Sample code

For more information about how to download the sample code, see SendMessageDemo.java.

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.common.utils.ServiceSettings;
import com.aliyun.mns.model.Message;

/**
 * 1. Configure the AccessKey ID and AccessKey secret in the environment based on Alibaba Cloud specifications. 
 * 2. Configure the ${"user.home"}/.aliyun-mns.properties file based on the following content:
 *           mns.endpoint=http://xxxxxxx
 *           mns.msgBodyBase64Switch=true/false
 */
public class SendMessageDemo {

    /**
     * replace with your queue name
     */
    private static final String QUEUE_NAME = "cloud-queue-demo";

    private static final Boolean IS_BASE64 = Boolean.valueOf(ServiceSettings.getMNSPropertyValue("msgBodyBase64Switch","false"));


    public static void main(String[] args) {
        // Configure the AccessKey ID and AccessKey secret in the environment based on Alibaba Cloud specifications. 
        CloudAccount account = new CloudAccount(ServiceSettings.getMNSAccountEndpoint());
        MNSClient client = account.getMNSClient();

        // Demo for send message code, send 10 test message
        try {
            CloudQueue queue = client.getQueueRef(QUEUE_NAME);
            for (int i = 0; i < 10; i++) {
                Message message = new Message();
                String messageValue = "demo_message_body" + i;
                if (IS_BASE64) {
                    // Encode the message body in Base64.
                    message.setMessageBody(messageValue);
                }else {
                    // Do not encode the message body.
                    message.setMessageBodyAsRawString(messageValue);
                }

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

}