import Stomp from 'stompjs'
class StompClient {
constructor(rmqServer, rmqVirtualHost, rmqAccount, rmqPassword) {
this.queueName = ''
this.client = null
this.frame = null
this.options = {
vhost: rmqVirtualHost,
incoming: 10000,
outgoing: 10000,
account: rmqAccount,
pwd: rmqPassword,
server: `ws://${rmqServer}/ws`,
message: ''
}
}
getQueueName() {
this.queueName = 'xxx'
}
connect(options) {
this.options = { ...this.options, ...options }
const mqUrl = this.options.server
const ws = new WebSocket(mqUrl)
ws.onclose = (close) => {
console.log('webSocket关闭', close)
}
ws.onerror = (error) => {
console.log('webSocket异常', error)
}
ws.onopen = (success) => {
console.log('webSocket连接成功', success)
}
this.client = Stomp.over(ws)
this.client.heartbeat.incoming = this.options.incoming
this.client.heartbeat.outgoing = this.options.outgoing
this.client.debug = null
const onConnect = async () => {
console.log('stomp 连接成功!')
this.subscribe()
}
const onError = (errorMsg) => {
console.error(`stomp 断开连接,正在准备重新连接...`, errorMsg)
this.connect(this.options)
}
this.client.connect(
this.options.account,
this.options.pwd,
onConnect,
onError,
this.options.vhost
)
}
subscribe() {
this.getQueueName()
if (!this.queueName) {
return
}
this.client.subscribe(
`/exchange/amq.direct/${this.queueName}`,
this.onMessage.bind(this),
this.onSubscribeFailed.bind(this),
{
'auto-delete': 'true'
}
)
}
closeConnect() {
this.client.disconnect(() => {
console.log('已关闭mq连接')
})
}
onMessage(frame) {
const data = frame && JSON.parse(frame.body)
console.log('data :>> ', data.index)
this.options.message = data
}
onSubscribeFailed(frame) {
console.log('rabbitmq subscribe failed')
}
}
const RMQ_SERVER = '10.0.0.0:15674'
const RMQ_VIRTUAL_HOST = 'xx'
const RMQ_ACCOUNT = 'xxx'
const RMQ_PASSWORD = 'xxx'
export default new StompClient(RMQ_SERVER, RMQ_VIRTUAL_HOST, RMQ_ACCOUNT, RMQ_PASSWORD)
watch: {
opt: {
deep: true,
immediate: true,
handler(newVal) {
this.fileDetail = (newVal && newVal.message) || {}
}
}
},