Get the online status of ApsaraMQ for MQTT clients

Updated at:
Copy as MD

ApsaraMQ for MQTT provides two methods to obtain the online status of its clients: synchronous query and asynchronous online and offline event notification. This topic describes the basic principles, application scenarios, differences, and implementation methods for these two approaches.

Basic principles

The ApsaraMQ for MQTT server provides the following methods to obtain the online status of clients:

  • Synchronous query

    This method is simple. You can call an OpenAPI operation over HTTP or HTTPS through an open endpoint to query the current real-time status of a specific client. This method is suitable for checking the status of one or more clients.

  • Asynchronous online and offline event notification

    This method uses message notifications. When a client goes online or offline, the MQTT server can push event messages directly to a cloud application deployed on an Alibaba Cloud server.

    This method lets you asynchronously detect changes in a client's status. It detects online and offline events, not the online status itself. Therefore, the cloud application must analyze the time series of these events to determine the client's current status.

Scenarios

The two methods for obtaining the online status of ApsaraMQ for MQTT clients are suitable for the following scenarios:

  • Synchronous query

    • You need to determine subsequent logic in the main business flow based on a client's online status.

    • You need to check whether a specific client is online as part of an Operations and Maintenance (O&M) procedure.

  • Asynchronous online and offline event notification

    • The server-side application needs to trigger predefined actions when a client goes online or offline.

    • The server-side application needs to perform statistical analysis on client online and offline data and push messages based on client online statuses.

Differences between synchronous query and asynchronous event notification

The differences between the two query methods are as follows:

  • A synchronous query retrieves the current, real-time status of a client. In theory, this method is more accurate than asynchronous notification.

  • Asynchronous online and offline notification uses message decoupling. This makes status determination more complex and increases the chance of inaccuracy. However, this method lets you analyze the status history of multiple clients based on events. Despite its complexity and potential for inaccuracy, asynchronous notification is better suited for collecting status statistics for many clients.

Implementation methods

  • Synchronous query

    You can obtain the client status by calling the following API operations:

  • Asynchronous online and offline event notification

    For asynchronous online and offline event notification, your cloud service can obtain client online and offline messages using the server-side software development kit (SDK) provided by ApsaraMQ for MQTT. For SDK downloads, see Version Guide.

    The following sample code shows how to retrieve client online and offline events:

    Note

    Before you use the sample code, configure environment variables for your access credentials. For more information about how to configure environment variables, see Configure access credentials.

    The environment variables for the AccessKey ID and AccessKey secret of ApsaraMQ for MQTT are MQTT_AK_ENV and MQTT_SK_ENV.

    package com.aliyun.openservices.lmq.example;
    
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.mqtt.server.ServerConsumer;
    import com.alibaba.mqtt.server.callback.StatusListener;
    import com.alibaba.mqtt.server.config.ChannelConfig;
    import com.alibaba.mqtt.server.config.ConsumerConfig;
    import com.alibaba.mqtt.server.model.StatusNotice;
    
    public class MQTTClientStatusNoticeProcessDemo {
        public static void main(String[] args) throws Exception {
             /**
             * The endpoint of the ApsaraMQ for MQTT instance that you created.
             * To get the endpoint for the server-side SDK, contact technical support. DingTalk group number: 116015007918.
             * You must use the assigned domain name for the endpoint address. Do not connect directly using an IP address. Otherwise, server-side exceptions may occur.
             */
            String domain = "domain";
    
             /**
             * The protocol and port must match. The value of this parameter is fixed at 5672.
             */
            int port = 5672;
    
             /**
             * The ID of the ApsaraMQ for MQTT instance that you created.
             */
            String instanceId = "instanceId";
    
            /**
             * The AccessKey ID for Alibaba Cloud identity verification. Create it in the Resource Access Management (RAM) console.
             * An Alibaba Cloud account AccessKey has access permissions for all API operations. We recommend that you use a RAM user for API access or daily O&M.
             * We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey leak, which threatens the security of all resources in your account.
             * This example shows how to save the AccessKey and AccessKey secret in environment variables.
             */
            String accessKey = System.getenv("MQTT_AK_ENV");
            /**
             * The AccessKey secret for Alibaba Cloud identity verification. Create it in the RAM console. You only need to set this in signature authentication mode.
             */
            String secretKey = System.getenv("MQTT_SK_ENV");
             
             /**
             * The ID of the group that you created in the ApsaraMQ for MQTT console.
             * */
            String mqttGroupId = "mqttGroupId";
    
            ChannelConfig channelConfig = new ChannelConfig();
            channelConfig.setDomain(domain);
            channelConfig.setPort(port);
            channelConfig.setInstanceId(instanceId);
            channelConfig.setAccessKey(accessKey);
            channelConfig.setSecretKey(secretKey);
    
            ServerConsumer serverConsumer = new ServerConsumer(channelConfig, new ConsumerConfig());
            serverConsumer.start();
            serverConsumer.subscribeStatus(mqttGroupId, new StatusListener() {
                @Override
                public void process(StatusNotice statusNotice) {
                    System.out.println(JSONObject.toJSONString(statusNotice));
                }
            });
        }
    
    }

More information

Data flow for online and offline events of ApsaraMQ for MQTT clients