vue中使用RabbitMQ

一、先安装依赖插件

// 先安装stompjs
npm install stompjs

二、组件中的使用

import Stomp from "stompjs";
import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD } from "../config/mqtt";

config文件中的mqtt.js内容:

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

组件中代码:

export default {
	data() {
		return {
			client: Stomp.client(MQTT_SERVICE)
    	};
  	},
  	created() {
		this.connect();
	},
	methods: {
		onConnected: function(frame) {
		  //订阅频道
	      const topic = "/exchange/BaseDataExchange/routeData.alarm.65";
	      this.client.subscribe(topic, this.responseCallback, this.onFailed);
	    },
	    onFailed: function(frame) {
	      console.log("MQ Failed: " + frame);
	    },
	    responseCallback: function(frame) {
	      console.log("MQ msg=>" + frame.body);
	      //接收消息处理
	    },
	    connect: function() {
	      //初始化mqtt客户端,并连接mqtt服务
	      const headers = {
	        login: MQTT_USERNAME,
	        passcode: MQTT_PASSWORD
	      };
	      this.client.connect(headers, this.onConnected, this.onFailed);
	    }
	}
};
Logo

前往低代码交流专区

更多推荐