首页 > 技术文章 > mq接收消息

minghan 2021-03-26 13:39 原文

<template></template>
<script>
import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD } from "../../config/mqtts";
import Stomp from "stompjs";
export default {
  data() {
    return {
      client: Stomp.client(MQTT_SERVICE)
    };
  },
  created() {
    //mq
    this.connect();
    console.log("mq===");
  },
  mounted() {},
  methods: {
    //以下监听mq异常
    onConnected: function (frame) {
      var topic = "队列名";
      console.log("queue:" + topic);
      this.client.subscribe(topic, this.responseCallback, this.onFailed);
    },
    onFailed: function (frame) {
      console.log("MQ Failed: " + frame);
      var that = this;
      setTimeout(function () {
        that.connect();
      }, 5000);
    },
    responseCallback: function (frame) {
      var frames = JSON.parse(frame.body);
      console.log("responseCallback msg=>", frames);
      console.log("------");
    },
    connect: function () {
      console.log("mq==========服务");
      //初始化mqtt客户端,并连接mqtt服务
      const headers = {
        login: MQTT_USERNAME,
        passcode: MQTT_PASSWORD,
      };
      this.client.connect(
        MQTT_USERNAME,
        MQTT_PASSWORD,
        this.onConnected,
        this.onFailed,
        "/"
      );
    },

  },
};
</script>
<style scoped></style>


//mqtts
export const MQTT_SERVICE = 'ws://' // mqtt服务地址 export const MQTT_USERNAME = '1' // mqtt连接用户名 export const MQTT_PASSWORD = '1' // mqtt连接密码

 

推荐阅读