Consume topic messages from a queue
When a queue subscribes to a topic in Simple Message Queue (formerly MNS), messages published to that topic are automatically pushed to the queue. Use SMQ SDK for Java to consume these messages in JSON, XML, or SIMPLIFIED format.
Prerequisites
SMQ SDK for Java is installed. For more information, see Install SDK for Java.
An endpoint and access credential are configured. For more information, see Configure endpoints and access credentials.
Message content formats
Topics push messages to subscribed queues in one of three formats. The format determines how to decode the message body.
| Subscription format | Base64 encoding | Send method | Consume method |
|---|---|---|---|
| SIMPLIFIED | Not required | RawTopicMessage | message.getMessageBodyAsRawString() |
| JSON | Required | TopicMessage | Parse the JSON envelope, extract the Message field, then Base64-decode |
| XML | Required | TopicMessage | Parse the XML document, extract the <Message> element, then Base64-decode |
JSON message structure
With JSON format, messages arrive wrapped in a JSON envelope:
{
"TopicOwner": "1234567890123456",
"Message": "SGVsbG8gV29ybGQ=",
"Subscriber": "1234567890123456",
"PublishTime": 1556123456789,
"SubscriptionName": "MySubscription",
"MessageMD5": "B10A8DB164E0754105B7A99BE72E3FE5",
"TopicName": "MyTopic",
"MessageId": "D6D5F7EC80B6417FAC4EB5954A366512"
}The original message content is in the Message field. If Base64 encoding is enabled, decode this field to retrieve the original text.
XML message structure
With XML format, messages arrive in this structure:
<?xml version="1.0" encoding="UTF-8"?>
<Notification xmlns="http://mns.aliyuncs.com/doc/v1/">
<TopicOwner>1234567890123456</TopicOwner>
<TopicName>MyTopic</TopicName>
<Subscriber>1234567890123456</Subscriber>
<SubscriptionName>MySubscription</SubscriptionName>
<MessageId>D6D5F7EC80B6417FAC4EB5954A366512</MessageId>
<Message>SGVsbG8gV29ybGQ=</Message>
<MessageMD5>B10A8DB164E0754105B7A99BE72E3FE5</MessageMD5>
<PublishTime>1556123456789</PublishTime>
</Notification>Extract the <Message> element and Base64-decode it to get the original text.
Sample code
This example uses long polling to batch-receive messages from a topic-subscribed queue. It automatically detects the message format (JSON, XML, or SIMPLIFIED) and decodes the body accordingly.
All configuration is loaded from the ${user.home}/.aliyun-mns.properties file:
mns.endpoint=http://<your-account-id>.mns.<region-id>.aliyuncs.com
mns.msgBodyBase64Switch=trueReplace the placeholders with your actual values:
| Placeholder | Description | Example |
|---|---|---|
<your-account-id> | Alibaba Cloud account ID | 1234567890123456 |
<region-id> | Region ID of the SMQ service | cn-hangzhou |
Set mns.msgBodyBase64Switch to true if the subscription uses JSON or XML format, or false for SIMPLIFIED format.
For the complete source file, see ConsumerQueueForTopicDemo.java on GitHub.
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;
import java.io.StringReader;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class ConsumerQueueForTopicDemo {
// Load the Base64 switch from the properties file. Defaults to false (SIMPLIFIED format).
private static final Boolean IS_BASE64 = Boolean.valueOf(
ServiceSettings.getMNSPropertyValue("msgBodyBase64Switch", "false"));
public static void main(String[] args) {
// Replace with the name of your topic-subscribed queue.
String QUEUE_NAME = "TestQueue";
// Initialize the client. Credentials are loaded from environment variables
// configured per Alibaba Cloud specifications.
CloudAccount account = new CloudAccount(ServiceSettings.getMNSAccountEndpoint());
MNSClient client = account.getMNSClient(); // Initialize once and reuse
CloudQueue queue = client.getQueueRef(QUEUE_NAME);
try {
longPollingBatchReceive(queue);
} catch (ClientException ce) {
System.out.println("Network error: check your network connection and DNS settings.");
ce.printStackTrace();
} catch (ServiceException se) {
if (se.getErrorCode().equals("QueueNotExist")) {
System.out.println("Queue does not exist. Create the queue before running this example.");
} else if (se.getErrorCode().equals("TimeExpired")) {
System.out.println("Request expired. Check that your local system clock is accurate.");
}
se.printStackTrace();
} catch (Exception e) {
System.out.println("Unexpected error occurred.");
e.printStackTrace();
}
client.close();
}
/**
* Batch-receive messages using long polling.
* Long polling reduces empty responses by waiting for messages to arrive
* before the request times out.
*/
private static void longPollingBatchReceive(CloudQueue queue) {
// Maximum number of messages to receive per batch
int batchSize = 15;
// Long polling timeout in seconds
int waitSeconds = 15;
List<Message> messages = queue.batchPopMessage(batchSize, waitSeconds);
if (messages != null && messages.size() > 0) {
for (Message message : messages) {
System.out.println("message handle: " + message.getReceiptHandle());
System.out.println("message body: " + message.getOriginalMessageBody());
System.out.println("message body real data: " + getMessageBodyData(message));
System.out.println("message id: " + message.getMessageId());
System.out.println("message dequeue count:" + message.getDequeueCount());
// Add your business logic here.
// Important: Always delete the message after successful processing.
// If not deleted, the message becomes visible again after the
// visibility timeout and is redelivered.
queue.deleteMessage(message.getReceiptHandle());
System.out.println("delete message successfully.\n");
}
}
}
/**
* Detect the message format and extract the original content.
* Parsing order: JSON -> XML -> Simple text (fallback).
*/
private static String getMessageBodyData(Message message) {
if (message == null) {
return null;
}
String originalMessageBody = message.getOriginalMessageBody();
// Step 1: Try to parse as JSON
try {
JSONObject object = new JSONObject(originalMessageBody);
String jsonMessageData = String.valueOf(object.get("Message"));
System.out.println("message body type: JSON, value:" + jsonMessageData);
return IS_BASE64 ? new String(Base64.decodeBase64(jsonMessageData)) : jsonMessageData;
} catch (JSONException ex1) {
// Not JSON format, try XML next
}
// Step 2: Try to parse as XML
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(originalMessageBody)));
Element root = doc.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("Message");
String content = nodeList.item(0).getTextContent();
System.out.println("message body type: XML, value:" + content);
return IS_BASE64 ? new String(Base64.decodeBase64(content)) : content;
} catch (Exception ex) {
// Not XML format, fall through to simple text
}
// Step 3: Treat as simple text (SIMPLIFIED format)
System.out.println("message body type: SIMPLE");
return IS_BASE64 ? message.getMessageBody() : message.getMessageBodyAsRawString();
}
}Key points
Client lifecycle: Initialize
MNSClientonce and reuse it across operations. Callclient.close()when finished.Message deletion: Always call
queue.deleteMessage()after successful processing. Undeleted messages become visible again after the visibility timeout and are redelivered.Format detection: The
getMessageBodyDatamethod tries JSON first, then XML, then falls back to simple text. This auto-detection works regardless of the subscription format.Base64 decoding: Set
mns.msgBodyBase64Switch=truein the properties file when the subscription uses JSON or XML format. For SIMPLIFIED format, set it tofalseor omit the property.
Error handling
| Exception | Error code | Cause | Action |
|---|---|---|---|
ClientException | N/A | Network or DNS failure | Check network connectivity and DNS resolution |
ServiceException | QueueNotExist | Queue has not been created | Create the queue and set up the topic subscription |
ServiceException | TimeExpired | System clock drift | Synchronize your local system clock |