Publish a message to a topic

Updated at:

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

Prerequisites

Before you begin, make sure that you have:

Message body encoding

SMQ supports both raw and Base64-encoded message bodies. If the message body does not contain special characters, use the raw methods to skip Base64 encoding:

OperationMethod
Set the message bodymessage.setMessageBodyAsRawString
Get the message bodymessage.getMessageBodyAsRawString

Sample code

The following example publishes a message to a topic. It reads the Base64 encoding preference from a local configuration file and selects the message type accordingly.

For the complete source code, see PublishMessageDemo.java on GitHub.

Configure credentials

Create the configuration file at ${"user.home"}/.aliyun-mns.properties:

mns.endpoint=http://xxxxxxx
mns.msgBodyBase64Switch=true/false

Replace http://xxxxxxx with your SMQ endpoint.

Configure the AccessKey ID and AccessKey secret as environment variables per Alibaba Cloud security best practices.

Publish a message

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;


public class PublishMessageDemo {
    // Read the Base64 encoding switch from the configuration file.
    // Default: false (raw message body, no encoding).
    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!";

        // Create an account object by using the endpoint from the configuration file.
        CloudAccount account = new CloudAccount(ServiceSettings.getMNSAccountEndpoint());

        // Initialize the client once and reuse it across publish calls.
        MNSClient client = account.getMNSClient();

        publishMsg(client, topicName, message);

        client.close();
    }

    private static void publishMsg(MNSClient client, String topicName, String message) {
        // Get a reference to the topic.
        CloudTopic topic = client.getTopicRef(topicName);

        // Select the message type based on the Base64 encoding switch.
        TopicMessage msg = IS_BASE64 ? new Base64TopicMessage() : new RawTopicMessage();

        try {
            msg.setMessageBody(message);

            // Optional: set a message filtering tag for subscriber-side filtering.
            // 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");
        }
    }
}

Key points

  • Client lifecycle: Initialize MNSClient once and reuse it for multiple publish operations. Call client.close() when all operations are complete to release resources.

  • Message type selection: RawTopicMessage sends the body as-is. Base64TopicMessage Base64-encodes the body before transmission. The example reads this preference from mns.msgBodyBase64Switch in the configuration file.

  • Message filtering: Call msg.setMessageTag("filterTag") before publishing to tag the message. Subscribers receive only messages whose tag matches their subscription filter.

  • Response fields: A successful publishMessage call returns a TopicMessage object that contains the request ID (getRequestId), message ID (getMessageId), and MD5 checksum of the message body (getMessageBodyMD5).

See also