天天看點

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

概述

您可以使用規則引擎,将物聯網平台資料轉發到消息隊列(RocketMQ)中存儲。進而實作消息從裝置、物聯網平台、RocketMQ到應用伺服器之間的全鍊路高可靠傳輸能力。文本從物聯網平台的産品及裝置的建立開始,逐漸介紹整個鍊路的完整實作。

操作步驟

1、建立物聯網産品及裝置

參考 阿裡雲物聯網平台Qucik Start 快速建立産品和裝置。

2、

RocketMQ控制台

建立執行個體、Topic和Group,這個為了友善本地測試消費MQ的消息,選擇在公網區域建立相關資源

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

3、配置規則引擎

a、配置總覽

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

b、處理資料

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

c、轉發資料

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

d、配置完開啟規則引擎

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

相關參考:

SQL語句參考 資料轉發到消息隊列RocketMQ

裝置上報屬性消息

import com.alibaba.taro.AliyunIoTSignUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.HashMap;
import java.util.Map;

public class IoTDemoPubSubDemo1 {
    public static String productKey = "*********";
    public static String deviceName = "*********";
    public static String deviceSecret = "*********";
    public static String regionId = "cn-shanghai";

    // 物模型-屬性上報topic
    private static String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";

    private static MqttClient mqttClient;

    public static void main(String [] args){

        // 初始化Mqtt Client對象
        initAliyunIoTClient();
        // 彙報屬性
        postDeviceProperties();

    }

    /**
     * 初始化 Client 對象
     */
    private static void initAliyunIoTClient() {

        try {
            // 構造連接配接需要的參數
            String clientId = "java" + System.currentTimeMillis();
            Map<String, String> params = new HashMap<>(16);
            params.put("productKey", productKey);
            params.put("deviceName", deviceName);
            params.put("clientId", clientId);
            String timestamp = String.valueOf(System.currentTimeMillis());
            params.put("timestamp", timestamp);
            // cn-shanghai
            String targetServer = "tcp://" + productKey + ".iot-as-mqtt."+regionId+".aliyuncs.com:1883";

            String mqttclientId = clientId + "|securemode=3,signmethod=hmacsha1,timestamp=" + timestamp + "|";
            String mqttUsername = deviceName + "&" + productKey;
            String mqttPassword = AliyunIoTSignUtil.sign(params, deviceSecret, "hmacsha1");

            connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);

        } catch (Exception e) {
            System.out.println("initAliyunIoTClient error " + e.getMessage());
        }
    }

    public static void connectMqtt(String url, String clientId, String mqttUsername, String mqttPassword) throws Exception {

        MemoryPersistence persistence = new MemoryPersistence();
        mqttClient = new MqttClient(url, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // MQTT 3.1.1
        connOpts.setMqttVersion(4);
        connOpts.setAutomaticReconnect(false);
//        connOpts.setCleanSession(true);
        connOpts.setCleanSession(false);

        connOpts.setUserName(mqttUsername);
        connOpts.setPassword(mqttPassword.toCharArray());
        connOpts.setKeepAliveInterval(60);

        mqttClient.connect(connOpts);
    }

    /**
     * 彙報屬性
     */
    private static void postDeviceProperties() {

        try {
            //上報資料
            //進階版 物模型-屬性上報payload
            System.out.println("上報屬性值");
            String payloadJson = "{\"params\":{\"Status\":1,\"Data\":\"33\"}}";
            MqttMessage message = new MqttMessage(payloadJson.getBytes("utf-8"));
            message.setQos(1);
            mqttClient.publish(pubTopic, message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}           

運作狀态顯示

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試
參考連結: 基于開源JAVA MQTT Client連接配接阿裡雲IoT

MQ Topic消息訂閱

1、pom.xml

<dependencies>
        <dependency>
            <groupId>com.aliyun.openservices</groupId>
            <artifactId>ons-client</artifactId>
            <version>1.8.0.Final</version>
        </dependency>
    </dependencies>           

2、Code Sample

import com.aliyun.openservices.ons.api.*;
import java.util.Properties;

public class ConsumerTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        // 您在控制台建立的 Group ID
        properties.put(PropertyKeyConst.GROUP_ID, "GID_****");
        // AccessKey 阿裡雲身份驗證,在阿裡雲伺服器管理控制台建立
        properties.put(PropertyKeyConst.AccessKey,"********");
        // SecretKey 阿裡雲身份驗證,在阿裡雲伺服器管理控制台建立
        properties.put(PropertyKeyConst.SecretKey, "********");

        properties.put(PropertyKeyConst.ConsumeThreadNums,50);
        // 設定 TCP 接入域名,進入控制台的執行個體管理頁面的“擷取接入點資訊”區域檢視
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
                "http://MQ_INST_184821781661****_BaQU****.mq-internet-access.mq-internet.aliyuncs.com:80");

        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe("Topic_MQDemo", "*", new MessageListener() { //訂閱多個 Tag
            public Action consume(Message message, ConsumeContext context) {
                System.out.println("Receive: " + message);
                System.out.println("Message : " + new String(message.getBody()));//列印輸出消息
                return Action.CommitMessage;
            }
        });
        consumer.start();
        System.out.println("Consumer Started");
    }
}           

3、測試結果

Receive: Message [topic=Topic_MQDemo, systemProperties={KEYS=1202850299555940352, __KEY=1202850299555940352, __RECONSUMETIMES=0, __BORNHOST=/11.115.104.187:51935, __MSGID=0B7368BB19AF531D72CA1D0A9B540077, MIN_OFFSET=520, __BORNTIMESTAMP=1575616834388, MAX_OFFSET=525}, userProperties={UNIQ_KEY=0B7368BB19AF531D72CA1D0A9B540077, MSG_REGION=cn-qingdao-publictest, eagleTraceId=0bc5f2c215756168339094214d0a1b, TRACE_ON=true, eagleData=s3bef5fb6, CONSUME_START_TIME=1575616834470, eagleRpcId=0.1.11.10.10.1.1.1.1}, body=38]
Message : {"data1":"33","deviceName":"MQDevice"}           

日志查詢(友善對問題進行跟蹤定位排查)

1、物聯網平台 -》 運維監控 -》 日志服務 -》 上行日志

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

2、消息隊列RocketMQ -》 消息查詢

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

AMQP服務端訂閱

1、管理門戶配置

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試
阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

2、代碼訂閱,參考

連結

3、Code Sample

import java.net.URI;
import java.util.Hashtable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AmqpJavaClientDemo {

    private final static Logger logger = LoggerFactory.getLogger(AmqpJavaClientDemo.class);

    public static void main(String[] args) throws Exception {
        //參數說明,請參見上一篇文檔:AMQP用戶端接入說明。
        String accessKey = "******";
        String accessSecret = "******";
        String consumerGroupId = "******";
        long timeStamp = System.currentTimeMillis();
        //簽名方法:支援hmacmd5,hmacsha1和hmacsha256
        String signMethod = "hmacsha1";
        //控制台服務端訂閱中消費組狀态頁用戶端ID一欄将顯示clientId參數。
        //建議使用機器UUID、MAC位址、IP等唯一辨別等作為clientId。便于您區分識别不同的用戶端。
        String clientId = "yutaodemotest";

logger.debug("demo");

        logger.error("error","this is my test error info.");
        logger.info("info");
        logger.error("error");

        //UserName組裝方法,請參見上一篇文檔:AMQP用戶端接入說明。
        String userName = clientId + "|authMode=aksign"
                + ",signMethod=" + signMethod
                + ",timestamp=" + timeStamp
                + ",authId=" + accessKey
                + ",consumerGroupId=" + consumerGroupId
                + "|";
        //password組裝方法,請參見上一篇文檔:AMQP用戶端接入說明。
        String signContent = "authId=" + accessKey + "&timestamp=" + timeStamp;
        String password = doSign(signContent,accessSecret, signMethod);
        //按照qpid-jms的規範,組裝連接配接URL。
        String connectionUrl = "failover:(amqps://******.iot-amqp.cn-shanghai.aliyuncs.com?amqp.idleTimeout=80000)"
                + "?failover.maxReconnectAttempts=10&failover.reconnectDelay=30";

        Hashtable<String, String> hashtable = new Hashtable<>();
        hashtable.put("connectionfactory.SBCF",connectionUrl);
        hashtable.put("queue.QUEUE", "default");
        hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        Context context = new InitialContext(hashtable);
        ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF");
        Destination queue = (Destination)context.lookup("QUEUE");
        // Create Connection
        Connection connection = cf.createConnection(userName, password);
        ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener);
        // Create Session
        // Session.CLIENT_ACKNOWLEDGE: 收到消息後,需要手動調用message.acknowledge()
        // Session.AUTO_ACKNOWLEDGE: SDK自動ACK(推薦)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.start();
        // Create Receiver Link
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(messageListener);
    }

    private static MessageListener messageListener = new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                byte[] body = message.getBody(byte[].class);
                String content = new String(body);
                String topic = message.getStringProperty("topic");
                String messageId = message.getStringProperty("messageId");
                System.out.println("Content:" + content);
                logger.info("receive message"
                        + ", topic = " + topic
                        + ", messageId = " + messageId
                        + ", content = " + content);
                //如果建立Session選擇的是Session.CLIENT_ACKNOWLEDGE,這裡需要手動ACK。
                //message.acknowledge();
                //如果要對收到的消息做耗時的處理,請異步處理,確定這裡不要有耗時邏輯。
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
        /**
         * 連接配接成功建立。
         */
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            logger.info("onConnectionEstablished, remoteUri:{}", remoteURI);
        }

        /**
         * 嘗試過最大重試次數之後,最終連接配接失敗。
         */
        @Override
        public void onConnectionFailure(Throwable error) {
            logger.error("onConnectionFailure, {}", error.getMessage());
        }

        /**
         * 連接配接中斷。
         */
        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
        }

        /**
         * 連接配接中斷後又自動重連上。
         */
        @Override
        public void onConnectionRestored(URI remoteURI) {
            logger.info("onConnectionRestored, remoteUri:{}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {}

        @Override
        public void onSessionClosed(Session session, Throwable cause) {}

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {}

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {}
    };

    /**
     * password簽名計算方法,請參見上一篇文檔:AMQP用戶端接入說明。
     */
    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }
}
           

4、測試結果

Content:{"deviceType":"None","iotId":"QyLOC9FsRiJePV*********","requestId":"null","productKey":"a1QVZRPkS5g","gmtCreate":1575632021248,"deviceName":"MQDevice","items":{"Status":{"value":1,"time":1575632021255},"Data":{"value":"33","time":1575632021255}}}           

5、服務端訂閱門戶監控

阿裡雲物聯網平台裝置資料轉發到消息隊列RocketMQ全鍊路測試

更多參考

控制台配置AMQP服務端訂閱 Rocket MQ訂閱消息