Push events from ApsaraMQ for MQTT to Function Compute

Updated at:

Route MQTT messages to Function Compute through EventBridge for serverless event processing.

How it works

EventBridge cannot pull events directly from ApsaraMQ for MQTT. Instead, the data outflow feature in ApsaraMQ for MQTT forwards messages to ApsaraMQ for RocketMQ, which then serves as a custom event source for EventBridge.

The data flows through four stages:

  1. An MQTT client publishes a message to a topic in ApsaraMQ for MQTT.

  2. A data outflow rule forwards the message to a topic in ApsaraMQ for RocketMQ.

  3. EventBridge receives the message from the RocketMQ custom event source.

  4. An event rule matches the message and delivers it to Function Compute.

Prerequisites

Before you begin, make sure that you have completed the following tasks:

Step 1: Create a data outflow rule

Configure a data outflow rule in the ApsaraMQ for MQTT console to forward messages to ApsaraMQ for RocketMQ.

  1. Log on to the ApsaraMQ for MQTT console. In the left-side navigation pane, click Instances.

  2. In the top navigation bar, select the region of your instance. Click the instance name to open the Instance Details page.

  3. In the left-side navigation pane, click Rules. In the upper-left corner, click Create Rule.

  4. In the Configure Basic Information step, set the following parameters and click Next.

    ParameterExampleDescription
    Rule ID111111A globally unique identifier for the rule. Can contain letters, digits, hyphens (-), and underscores (_). Must contain at least one letter or digit and be 3 to 64 characters in length. If the value contains more than 64 characters, it is automatically truncated. Cannot be changed after creation.
    Descriptionmigrate from rocketmqA description of the rule.
    StatusEnableWhether to enable the rule. Valid values: Enable, Disable.
    Rule TypeData OutboundThe type of the rule. Valid values: Data Outbound: exports data from ApsaraMQ for MQTT to other Alibaba Cloud services. For more information, see Export data from ApsaraMQ for MQTT to other Alibaba Cloud services. Data Inbound: imports data from other Alibaba Cloud services to ApsaraMQ for MQTT. For more information, see Import data from other cloud services to ApsaraMQ for MQTT. Client Status Notification: exports online and offline events of ApsaraMQ for MQTT clients to other Alibaba Cloud services. For more information, see Export online and offline events of Message Queue for MQTT clients.
  5. In the Configure Rule Source step, specify the source topic and click Next.

    ParameterExampleDescription
    TopicTopicAThe MQTT topic from which to export data.
  6. In the Configure Rule Destination step, specify the destination and click Create.

    ParameterExampleDescription
    Destination Service TypeMessage Queue for Apache RocketMQThe target service. Only ApsaraMQ for RocketMQ is supported.
    Message Queue for Apache RocketMQ InstanceMQ_INST_138015630\*\*\*\*\*\_BbyOD2jQThe RocketMQ instance ID. The instance must be in the same region as the MQTT instance.
    TopicTopicBThe RocketMQ topic to receive the forwarded data.

After creation, the rule appears on the Rules page.

Step 2: Create a custom event source

Add ApsaraMQ for RocketMQ as a custom event source in EventBridge.

  1. Log on to the EventBridge console.

  2. In the left-side navigation pane, click Event Buses.

  3. In the top navigation bar, select a region.

  4. On the Event Buses page, click the name of the custom event bus that you created.

  5. In the left-side navigation pane, click Event Sources.

  6. Click Add Event Source.

  7. In the Add Custom Event Source panel, configure Name and Description, then select ApsaraMQ for RocketMQ from the Event Provider drop-down list. Follow the on-screen instructions to select the RocketMQ resources you created, and click OK.

Step 3: Create an event rule

Define an event rule that routes events from the custom event source to Function Compute.

Important

Event targets must reside in the same region as the event rule.

  1. Log on to the EventBridge console. In the left-side navigation pane, click Event Buses.

  2. In the top navigation bar, select a region. Click the name of the event bus to manage.

  3. In the left-side navigation pane, click Event Rules. Click Create Rule.

  4. In the Configure Basic Info step, enter a rule name and description, then click Next Step.

  5. In the Configure Event Pattern step, set Event Source Type to Custom Event Source and select the event source you created in Step 2 from the Event Source drop-down list. Specify an event pattern in the Pattern Content editor and click Next step. For more information, see Event patterns.

  6. In the Configure Targets step, configure the event target and click Create.

    Note

    Each event rule supports up to five event targets.

    ParameterDescription
    Service TypeSelect Function Compute.
    FunctionSelect the function you created.
    EventSelect Complete Event, Partial Event, Fixed Value, or Template. In this example, Template is selected. For more information, see Event Transformation. Sample variables: {"source":"$.source","type":"$.type"}. Sample template: The event comes from ${source},event type is ${type}.
    Version and AliasSelect Specified Version or Specified Alias, then configure the version or alias.
    Invocation ModeSelect Synchronous or Asynchronous. Synchronous: returns the result after the function processes the event. Asynchronous: returns a response immediately after the request is persisted. For more information, see Synchronous invocations and Asynchronous invocations.
    Event FormatThe format in which events are delivered to the function. Object: delivered as objects. ObjectList: delivered as arrays. Default: Object.
    Retry Policy and Dead-letter QueueFor more information, see Retry policies and dead-letter queues.

Step 4: Publish a test message

Publish an MQTT message to verify the pipeline. The message flows through the data outflow rule to RocketMQ, then through EventBridge to Function Compute.

The following Java example uses the Eclipse Paho MQTT v3 client library with signature-based authentication. Replace the placeholders with your actual values before running the code.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * Publishes MQTT messages using signature-based authentication.
 * Uses the AccessKey ID and AccessKey secret from RAM to generate a signature.
 *
 * For the complete demo project, see https://github.com/AliwareMQ/lmq-demo.
 */
public class MQ4IoTProducerDemo {
    public static void main(String[] args) throws Exception {
        // ApsaraMQ for MQTT instance ID (from the MQTT console)
        String instanceId = "<your-instance-id>";

        // Instance endpoint (from the MQTT console, use the domain name, not an IP address)
        String endPoint = "<your-instance-id>.mqtt.aliyuncs.com";

        // AccessKey pair from environment variables
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String secretKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

        // Client ID in GroupID@@@DeviceID format (max 64 characters, unique per TCP connection)
        String clientId = "<your-group-id>@@@<your-device-id>";

        // Parent topic (created in the MQTT console)
        final String parentTopic = "<your-parent-topic>";

        // Subtopic for message filtering
        final String mq4IotTopic = parentTopic + "/" + "testMq4Iot";

        // QoS level: 0, 1, or 2
        final int qosLevel = 0;

        ConnectionOptionWrapper connectionOptionWrapper =
            new ConnectionOptionWrapper(instanceId, accessKey, secretKey, clientId);
        final MemoryPersistence memoryPersistence = new MemoryPersistence();

        // TCP connection on port 1883 (for SSL, use ssl://endpoint:8883)
        final MqttClient mqttClient =
            new MqttClient("tcp://" + endPoint + ":1883", clientId, memoryPersistence);

        // Response timeout in milliseconds
        mqttClient.setTimeToWait(5000);

        final ExecutorService executorService = new ThreadPoolExecutor(
            1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

        mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                System.out.println("connect success");
            }

            @Override
            public void connectionLost(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                // Consume messages within the broker's timeout period.
                // The broker may resend messages not consumed in time, so implement
                // deduplication to ensure idempotence. For details, see Limits.
                System.out.println(
                    "receive msg from topic " + s + " , body is " + new String(mqttMessage.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                System.out.println("send msg succeed topic is : " + iMqttDeliveryToken.getTopics()[0]);
            }
        });

        mqttClient.connect(connectionOptionWrapper.getMqttConnectOptions());

        // Publish 10 messages to the subtopic
        for (int i = 0; i < 10; i++) {
            MqttMessage message = new MqttMessage("hello mq4Iot pub sub msg".getBytes());
            message.setQos(qosLevel);
            mqttClient.publish(mq4IotTopic, message);

            // P2P messaging example: send directly to a specific client
            // Topic format: {parentTopic}/p2p/{targetClientId}
            String receiverId = "xxx";
            final String p2pSendTopic = parentTopic + "/p2p/" + receiverId;
            message = new MqttMessage("hello mq4Iot p2p msg".getBytes());
            message.setQos(qosLevel);
            mqttClient.publish(p2pSendTopic, message);
        }
        Thread.sleep(Long.MAX_VALUE);
    }
}

Replace the following placeholders with your actual values:

PlaceholderDescriptionExample
<your-instance-id>ApsaraMQ for MQTT instance IDmqtt-cn-xxx
<your-group-id>Consumer group ID from the MQTT consoleGID_test
<your-device-id>Custom device identifierdevice001
<your-parent-topic>Parent topic created in the MQTT consoleTopicA

Verify the result

Confirm that the function received and processed the event by checking the Function Compute logs.

  1. Log on to the Function Compute console.

  2. In the left-side navigation pane, click Functions. In the top navigation bar, select the region of your function.

  3. Click the function name to open the Function Details page.

  4. Click the Logs tab, then click Function Logs.

If the pipeline works correctly, the logs contain the event data delivered from ApsaraMQ for MQTT through EventBridge. Look for entries that include the message payload published in Step 4, such as hello mq4Iot pub sub msg. If no log entries appear, verify that each stage of the pipeline is configured correctly by working backward from EventBridge event tracing to the MQTT data outflow rule.

Function Compute logs showing received events

FAQ

How do I troubleshoot a failed event delivery?

Open the EventBridge console and go to the Event Trace page. Find the failed event in the Event Delivery section -- the delivery response shows the specific error and helps identify the root cause.

What does the "[500]ConnectErrorconnectiontimedout" error mean?

This error indicates a network connectivity issue between EventBridge and Function Compute.

  1. Log on to the Function Compute console and run the target function manually. Check the execution duration.

  2. If execution takes longer than 15 seconds, check your network configuration.

  3. If execution completes in under 15 seconds, verify that the Function Compute endpoint for your region is accessible.

  4. If the endpoint is not accessible, contact Function Compute support.