You can pull MO messages (SmsUp) by using Lightweight Message Queue (formerly MNS).
Prerequisites
-
You have registered an Alibaba Cloud account and generated an access key (AccessKey). For more information, see Create an AccessKey for a RAM user.
-
Make sure you can ping the following endpoints from your local machine:
dysmsapi.aliyuncs.com,mns.cn-hangzhou.aliyuncs.com(for the China (Hangzhou) region), ordybaseapi.aliyuncs.com. -
You have created a RAM user and granted it Short Message Service permissions and Lightweight Message Queue permissions.
-
You have read Configure message receipts and understand the receipt message modes, types, and configuration process.
SmsUp message body format
|
Parameter |
Type |
Example |
Description |
|
dest_code |
String |
123456 |
The extended SMS number. The system automatically generates this number, and you cannot customize it. |
|
send_time |
String |
2021-09-06 15:53:20 |
The time when the carrier pushed the MO message. |
|
sequence_id |
Double |
123456 |
The message sequence ID. |
|
phone_number |
String |
159****0532 |
The recipient number. |
|
content |
String |
123456 |
The message content. |
Download the demo
See Lightweight Message Queue (formerly MNS) consumer demo to download the demo and SDK for your preferred programming language. This topic uses Java as an example.
-
After you download the demo, the
libdirectory contains the required JAR packages. Import them by clicking Add as Library. -
You can find the Maven dependencies in the
pom.xmlfile and install the Alibaba Cloud SDK for Java.
Configure parameters
Before using the sample code, configure the following parameters.
Access key
Complete sample code
The dealMessage method processes received MO messages. Add your business logic to this method.
// Parse the message body based on the message format described in the documentation.
String arg = (String) contentMap.get("arg");
// Write your business code.
arg represents a parameter in the receipt message body that can be set to dest_code, send_time, sequence_id, phone_number, or content.
package com.alicom.mns.sample;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alicom.mns.tools.DefaultAlicomMessagePuller;
import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.google.gson.Gson;
/**
* This demo is used to receive messages from Alibaba Cloud Communication services only. Do not use it to receive messages from other services.
*/
public class ReceiveDemo {
private static Log logger=LogFactory.getLog(ReceiveDemo.class);
static class MyMessageListener implements MessageListener{
private Gson gson=new Gson();
@Override
public boolean dealMessage(Message message) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Key message attributes
System.out.println("message receiver time from mns:" + format.format(new Date()));
System.out.println("message handle: " + message.getReceiptHandle());
System.out.println("message body: " + message.getMessageBodyAsString());
System.out.println("message id: " + message.getMessageId());
System.out.println("message dequeue count:" + message.getDequeueCount());
System.out.println("Thread:" + Thread.currentThread().getName());
try{
Map<String,Object> contentMap=gson.fromJson(message.getMessageBodyAsString(), HashMap.class);
// Parse the message body based on the message format described in the documentation.
String arg = (String) contentMap.get("arg");
// Start writing your business code here.
}catch(com.google.gson.JsonSyntaxException e){
logger.error("error_json_format:"+message.getMessageBodyAsString(),e);
// A JSON syntax error should not happen. If it does, return `true` to delete the message and prevent it from being redelivered.
return true;
} catch (Throwable e) {
// If your business logic throws an exception, return `false` to retry message processing.
return false;
}
// Message processed successfully. Return `true` to delete it from the queue.
return true;
}
}
public static void main(String[] args) throws Exception, ParseException {
DefaultAlicomMessagePuller puller=new DefaultAlicomMessagePuller();
// Configure the asynchronous thread pool.
puller.setConsumeMinThreadSize(6);
puller.setConsumeMaxThreadSize(16);
puller.setThreadQueueSize(200);
puller.setPullMsgThreadSize(1);
// Enable this option only when you troubleshoot issues with the server. Otherwise, keep it disabled to reduce overhead.
puller.openDebugLog(false);
// Retrieve the access key from environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
/*
* Replace messageType and queueName with the message type and the corresponding queue name that you need.
* All receipt message types for Alibaba Cloud Communication services:
* 1. SMS receipts: SmsReport
* 2. MO messages: SmsUp
* 3. International SMS receipts: GlobeSmsReport
*/
String messageType="<MESSAGE_TYPE>"; // Replace this value with the message type for the corresponding product.
String queueName="<QUEUE_NAME>"; // Obtain the queue name from the Short Message Service console after enabling MNS. It will look like `Alicom-Queue-******-SmsUp`.
puller.startReceiveMsg(accessKeyId,accessKeySecret,messageType,queueName,new MyMessageListener());
}
}
After you run the demo, the output is similar to the following.
/Library/Java/JavaVirtualMachines/jdk1.8.0_291.jdk/Contents/Home/bin/java ...
Connected to the target VM, address: '127.0.0.1:62393', transport: 'socket'
14:00:07.056 [PullMessageTask-thread-0] DEBUG com.aliyun.mns.client.CloudAccount - initiated CloudAccount, accessId: xxx accessKey=xxx
message receiver time from mns: xxx
message handle: xxx
message body: xxx
message id: xxx
message dequeue count:1
Thread:pool-1-thread-1