问题描述:stompjs断连重连后一直连接不上,一直Opening web Socket …
原因:一个实例只能connect一次,重新new 对象
stompjs源码片段:(stompjs文档)
函数内部new Client返回新的一个对象,Stomp.over(ws)执行一次就是一个新对象文章来源:https://www.toymoban.com/news/detail-522546.html
vue+stompjs接收mq消息完整代码文章来源地址https://www.toymoban.com/news/detail-522546.html
<template>
<div></div>
</template>
<script>
import Stomp from "stompjs"
export const MQTT_SERVICE = location.protocol === 'https:'
? 'wss://xxx/ws'
: 'ws://xxx:15674/ws' // mqtt服务地址(https需要用wss协议)
export const MQTT_USERNAME = 'xxx' // mqtt连接用户名
export const MQTT_PASSWORD = 'xxx' // mqtt连接密码
export default {
data() {
return {
client: Stomp.client(MQTT_SERVICE),
};
},
created() {
this.connect();
},
methods: {
onConnected: function(frame) {
this.client.heartbeat.outgoing = 20000;
this.client.heartbeat.incoming = 0;
console.log("Connected: " + frame);
//订阅事件
const event = "xxx"; //topic
this.client.subscribe(event, this.responseCallback);
//订阅状态
const sataus = "xxx"; //topic
this.client.subscribe(sataus, this.responseCallback);
},
onFailed: function(frame) {
console.log("MQ Failed: " + frame);
//******需要加下列代码才能重新new 对象连接
this.client = Stomp.client(MQTT_SERVICE); //一个实例只能connect一次,得new个新的实例才可能进行新的connect
Stomp.over(this.client);
//失败重连
this.connect();
},
responseCallback: function(frame) {
//接收消息处理
console.log("MQ msg=>" + frame.body);
if (frame.body){
//...逻辑处理
}
},
connect: function() {
//初始化mqtt客户端,并连接mqtt服务
const headers = {
login: MQTT_USERNAME,
passcode: MQTT_PASSWORD,
host: 'xxx'
};
this.client.connect(headers, this.onConnected, this.onFailed);
},
},
};
</script>
到了这里,关于【vue+ stompjs接收rabbitMQ消息(断连重连mq问题】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!