//1、首先安装stomp
yarn add stompjs
yarn add sockjs-client
//2、引入
import Stomp from 'stompjs';
let client;
//mpData为传过来的参数。里面包含基本的用户名,密码,主机,超时时间等等
export function MqMessage(mpData) {
client = Stomp.client(mpData.url);
let value = null;
var headers = {
login: mpData.username,
passcode: mpData.userpwd,
//虚拟主机,默认“/”
host: mpData.vhost,
// 'accept-version': '1.1,1.0',
// 'heart-beat': '100000,10000',
// 'client-id': 'my-client-id'
};
//创建连接,放入连接成功和失败回调函数
client.connect(headers, onConnected, onFailed);
function onConnected(frame) {
// console.log('Connected: ' + frame);
//绑定交换机exchange_pushmsg是交换机的名字rk_pushmsg是绑定的路由key
//如果不用通过交换机发则如下直接写队列名称就行
var exchange = mpData.queue;
//创建随机队列用上面的路由key绑定交换机,放入收到消息后的回调函数和失败的回调函数
//是交换机把下面/queue/改为/exchange/
client.subscribe('/queue/' + exchange, responseCallback, {
ack: 'client',
'x-message-ttl': mpData.args['x-message-ttl'], //这个为我的超时时间
durable: true,
});
// console.log(frame);
}
function onFailed(frame) {
// console.log('Failed: ' + frame);
if (client.connected) {
client.disconnect(function () {
client.connect(headers, onConnected, onFailed);
});
}
else {
client.connect(headers, onConnected, onFailed);
}
}
function responseCallback(frame) {
value = frame.body;
// console.log('得到的消息 msg=>' + frame.body);
// console.log(frame);
//接收到服务器推送消息,向服务器定义的接收消息routekey路由rk_recivemsg发送确认消息
frame.ack();
}
// return value;
}
// 断开连接
export function DisMqMessage() {
try {
if (client.connected) {
client.disconnect();
}
} catch (e) {}
}
vue3利用Stomp连接rabbitMq接收后台消息
于 2022-07-22 15:14:35 首次发布