All Products
Search
Document Center

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

Last Updated:Oct 22, 2024

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

Prerequisites

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 PublishMessageDemo.java.

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.utils.ServiceSettings;
import com.aliyun.mns.model.Base64TopicMessage;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;


/**
 * 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 PublishMessageDemo {
    private static final Boolean IS_BASE64 = Boolean.valueOf(ServiceSettings.getMNSPropertyValue("msgBodyBase64Switch","false"));

    public static void main(String[] args) {
        String topicName = "TestTopic";
        String message = "hello world!";

        CloudAccount account = new CloudAccount(ServiceSettings.getMNSAccountEndpoint());
        //this client need only initialize once
        MNSClient client = account.getMNSClient();

        publishMsg(client, topicName, message);

        client.close();
    }

    private static void publishMsg(MNSClient client, String topicName, String message) {

        CloudTopic topic = client.getTopicRef(topicName);
        TopicMessage msg = IS_BASE64 ?  new Base64TopicMessage() : new RawTopicMessage();
        try {
            msg.setMessageBody(message);
            // Optional. Specify a filtering tag for the message.
            //msg.setMessageTag("filterTag");
            TopicMessage publishResultMsg = topic.publishMessage(msg);
            System.out.println("message publish.");
            System.out.println("reqId:"+publishResultMsg.getRequestId());
            System.out.println("msgId:"+publishResultMsg.getMessageId());
            System.out.println("md5:"+publishResultMsg.getMessageBodyMD5());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("publishMsg error");
        }
    }
}