Send a message to a queue
Send messages to a Simple Message Queue (formerly MNS) (SMQ) queue using the SMQ SDK for Java, with options for delayed delivery and Base64 encoding.
Prerequisites
Before you begin, make sure that you have:
Authorization
By default, only Alibaba Cloud accounts can call the SendMessage operation. To call this operation as a Resource Access Management (RAM) user, grant the required permissions first.
Name | Value |
API |
|
Action |
|
Resource |
|
Delayed delivery
By default, a message enters the Active state and becomes available for immediate consumption after being sent to a queue.
To delay consumption, set DelaySeconds to a value greater than 0. The message enters the Delayed state first and transitions to Active only after the specified delay period ends.
If both the message and the queue define DelaySeconds, the message-level value takes precedence.
Message body encoding
Encode the message body in Base64 to prevent errors caused by special characters. If the message body does not contain special characters, skip Base64 encoding and use the raw string methods instead.
| Scenario | Send method | Receive method |
|---|---|---|
| Base64 encoding | message.setMessageBody | message.getMessageBody |
| Raw string (no encoding) | message.setMessageBodyAsRawString | message.getMessageBodyAsRawString |
Send a message
This example connects to SMQ, sends messages to a queue, and handles errors.
For the complete source file, see SendMessageDemo.java on GitHub.
Step 1: Import dependencies and configure constants
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;
public class SendMessageDemo {
// Replace with your queue name
private static final String QUEUE_NAME = "cloud-queue-demo";
// Read the Base64 encoding switch from the config file (default: false)
private static final Boolean IS_BASE64 =
Boolean.valueOf(ServiceSettings.getMNSPropertyValue("msgBodyBase64Switch", "false"));The SDK reads the endpoint and credentials from ${"user.home"}/.aliyun-mns.properties:
mns.endpoint=http://xxxxxxx
mns.msgBodyBase64Switch=trueStep 2: Create the client
public static void main(String[] args) {
// Initialize the client from the config file endpoint.
// The SDK reads the AccessKey ID and AccessKey secret from environment variables.
CloudAccount account = new CloudAccount(ServiceSettings.getMNSAccountEndpoint());
MNSClient client = account.getMNSClient();Step 3: Send messages to the queue
try {
CloudQueue queue = client.getQueueRef(QUEUE_NAME);
for (int i = 0; i < 10; i++) {
Message message = new Message();
String body = "demo_message_body" + i;
if (IS_BASE64) {
// Base64-encode the message body
message.setMessageBody(body);
} else {
// Send the message body as a raw string
message.setMessageBodyAsRawString(body);
}
Message result = queue.putMessage(message);
System.out.println("Send message id is: " + result.getMessageId());
}Step 4: Handle errors and close the client
} catch (ClientException ce) {
System.out.println("Something wrong with the network connection between client and MNS service. "
+ "Please check your network and DNS availability.");
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();
}
}| Error code | Cause | Action |
|---|---|---|
QueueNotExist | The queue does not exist | Create the queue before sending messages |
TimeExpired | The request timestamp is out of sync | Verify the system clock on your local machine |
Expected output
On success, the console prints a message ID for each message sent:
Send message id is: 5F20B000F0E94A39-1-182B5C2****
Send message id is: 5F20B000F0E94A39-1-182B5C2****
...Endpoint selection
Choose the endpoint type based on your deployment environment:
| Scenario | Endpoint type | When to use |
|---|---|---|
| Development and testing | Public endpoint | Access SMQ from outside the Alibaba Cloud network |
| Production | Internal endpoint | Access SMQ from within the same region for lower latency and no data transfer fees |
For a full list of supported regions and endpoints, see Regions and endpoints.