Publish a message to a topic
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:
SMQ SDK for Java installed. For more information, see Install SDK for Java
An endpoint and access credential configured. For more information, see Configure endpoints and access credentials
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:
| Operation | Method |
|---|---|
| Set the message body | message.setMessageBodyAsRawString |
| Get the message body | message.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/falseReplace 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
MNSClientonce and reuse it for multiple publish operations. Callclient.close()when all operations are complete to release resources.Message type selection:
RawTopicMessagesends the body as-is.Base64TopicMessageBase64-encodes the body before transmission. The example reads this preference frommns.msgBodyBase64Switchin 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
publishMessagecall returns aTopicMessageobject that contains the request ID (getRequestId), message ID (getMessageId), and MD5 checksum of the message body (getMessageBodyMD5).