Code samples for Lightweight Message Queue (formerly MNS)

Updated at:

This topic provides message receipt samples for popular programming languages. You can download the corresponding SDK packages to pull messages from a queue in Simple Message Queue (formerly MNS).

Downloads

Note

The SDK download links provide the Alibaba Cloud Communications SDK core library for each supported language and the dybaseapi package. The dybaseapi package is used to pull messages from a queue.

Language

SDK download link

Java

Java SDK

Notes

Note the following information when you use the code samples.

  • Configure the AccessKey ID and AccessKey secret.

    To prevent your AccessKey pair from being leaked, do not hard-code it in your code. Instead, retrieve the AccessKey pair from environment variables. For more information about how to configure environment variables, see Configure environment variables on Linux, macOS, and Windows.

    This topic uses the environment variable names ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as examples. The following code shows how to retrieve an AccessKey pair from environment variables:

    String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
  • Replace messageType with the message type that you need, such as ChatAppInbound for mobile originated messages from the WhatsApp channel. For more information about the message receipt types that Chat App Message Service supports, see Introduction to and configuration of message receipts.

    String messageType="messageType";
  • queueName is the name of the message queue. For the WhatsApp channel, you can enable and save the message queue on the Chat App Message Service console > Instant Message > WhatsApp > Manage > WABA Management > Number Management > Set Webhook page. Then, go back to the Set Webhook page to view the queue name.

    String queueName="queueName";
  • In the Java code sample, the dealMessage method processes the mobile originated message content. You can add your business logic for the message content to this method. The arg parameter represents the message receipt body. Valid values include start_time, end_time, duration, and status_code. Specify the parameter based on your requirements.

    // Parse the message body based on the specific message format in the documentation.
    String arg = (String) contentMap.get("arg");
    // Write your business logic.

Code samples

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 com.alicom.mns.tools.DefaultAlicomMessagePuller;
import com.alicom.mns.tools.MessageListener;
import com.aliyun.mns.model.Message;
import com.google.gson.Gson;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This can be used to receive messages only from Alibaba Cloud Communications, not from other services.
 * A demo for receiving mobile originated text messages.
 */
public class ReceiveDemo {

    private static Logger logger = Logger.getLogger(ReceiveDemo.class.getName());

    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 values of the message
            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);

                // TODO: Parse the message body based on the specific message format in the documentation.
                String arg = (String) contentMap.get("arg");

                // TODO: Write your business logic here.

            } catch (com.google.gson.JsonSyntaxException e) {
                logger.log(Level.SEVERE, "error_json_format:" + message.getMessageBodyAsString(), e);
                // In theory, format errors do not occur. If a message has a format error, delete it. Otherwise, redelivery also fails.
                return true;
            } catch (Throwable e) {
                // If an exception is caused by your code, return false. This way, the message is not deleted and is redelivered based on the policy.
                return false;
            }

            // If the message is processed, return true. The SDK then calls the delete method of MNS to delete the message from the queue.
            return true;
        }

    }

    public static void main(String[] args) throws Exception, ParseException {

        DefaultAlicomMessagePuller puller = new DefaultAlicomMessagePuller();

        // Set the size of the asynchronous thread pool and task queue, and the thread hibernation time when no data is available.
        puller.setConsumeMinThreadSize(6);
        puller.setConsumeMaxThreadSize(16);
        puller.setThreadQueueSize(200);
        puller.setPullMsgThreadSize(1);
        // Enable this for server-side joint debugging. Do not enable it during normal use because it consumes performance.
        puller.openDebugLog(false);

        // TODO: Get the AccessKey information from the operating system.
        String accessKeyId=System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
	String accessKeySecret=System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

        /*
         * TODO: Replace messageType and queueName with the message type name and queue name that you need.
         * For all receipt message types that Chat App Message Service supports, see the following topic:
         * https://help.aliyun.com/zh/chatapp/developer-reference/configure-message-receipts
         */

        // Replace this with the message type of the corresponding product.
        String messageType = "messageType";
        // After you enable the message service for the business on the Alibaba Cloud Communications page, you can find the queueName on the page. The format is similar to Alicom-Queue-******-ChatAppInbound.
        String queueName = "queueName";

        puller.startReceiveMsg(accessKeyId, accessKeySecret, messageType, queueName, new MyMessageListener());
    }


}