vue连接RabbitMq
node环境下安装RabbitMq的javascript客户端 stompjs
npm install stompjs
在RabbbitMq开启 stomp
协议的端口
rabbitmq-plugins enable rabbitmq_web_stomp
参考文档:https://www.rabbitmq.com/web-stomp.html
创建vue组件进行连接
<template>
<div>
</div>
</template>
<script>
import {Client} from "@stomp/stompjs"
export default {
name: "test",
data() {
return {
client: null,
}
},
methods: {
connect() {
let url = "ws://localhost:15674/ws"
// 连接mq 的配置
let conf = {
brokerURL: url,
// 登录账户的用户名和密码
connectHeaders: {
login: "admin",
passcode: "admin"
}
}
// 初始化客户端
this.client = new Client(conf)
// 连接成功的回调函数
this.client.onConnect = (x) => {
console.log("成功---", x)
this.client.publish({destination: "test", body: "Hello, STOMP"})
let callback = function (message) {
console.log("消费。。。。")
console.log(message.body)
}
let subscription = this.client.subscribe("test", callback);
this.client.publish({destination: "test", body: "Hello, STOMP2"})
}
// 连接mq
this.client.activate()
},
},
mounted() {
this.connect()
}
}
</script>
连接成功后可以发送消息和消费消息等行为
参考文档:https://stomp-js.github.io/api-docs/latest/classes/Client.html