前期准备工作:安装完rabbitMq后需要启动stomp插件:

rabbitmq-plugins enable rabbitmq_web_stomp rabbitmq_stomp rabbitmq_web_stomp_examples

打开mq查看stomp服务是否配置成功 

 

 1.install stomps 依赖

npm install stomps

2.script

<script>
    import  Stomp from 'stompjs';
    import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD,MQTT_host,MQTT_topic } from '@/utils/mqtt'
    export default {
        name: "index",
        data() {
            return{
                client: Stomp.client(MQTT_SERVICE)
            }
        },
        mounted(){
            this.connect();
        },

        methods:{
            onConnected:function(){
                //订阅的频道
                const topic = MQTT_topic;
                this.client.subscribe(topic,this.responseCallback,this.onFailed);
            },
            onFailed:function(msg){
                console.log("MQ Failed:" + msg);
            },
            //成功时的回调函数
            responseCallback:function(msg){
                //接收消息的处理
                console.log("MQ msg=>" + msg.body);
            },
            //连接
            connect:function(){
                const headers = {
                    login: MQTT_USERNAME,
                    password: MQTT_PASSWORD
                };
                this.client.connect(headers,this.onConnected,this.onFailed);
            },
        },
        watch:{

        }
    }
</script>

3.mtt.js

export const MQTT_SERVICE = 'ws://你的ip:15674/ws' // mqtt服务地址
export const MQTT_USERNAME = 'admin' // mqtt连接用户名
export const MQTT_PASSWORD = 'admin' // mqtt连接密码
export const MQTT_topic = '/queue/demand.msg'//主题

 

Logo

前往低代码交流专区

更多推荐