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