123456789101112131415161718192021222324252627282930313233343536373839404142 |
- import { Client } from '@stomp/stompjs'
- import { isObject, get } from 'lodash-es'
- let client
- const options = {
- brokerURL: 'ws://localhost:15674/ws',
- connectHeaders: {
- host: 'hxmsg',
- login: 'huaxin',
- passcode: '1234qwerasdf'
- },
- reconnectDelay: 5000,
- heartbeatIncoming: 4000,
- heartbeatOutgoing: 4000
- }
- /**
- * 初始化stomp并订阅指定地址
- * @param {Object} subscribes 订阅配置 {[url]:(msg)=>{}} key:订阅地址;value:回调函数
- * @returns
- */
- const initClient = (subscribes) => {
- client = new Client(options)
- client.onConnect = (res) => {
- console.log('is connected')
- if (!isObject(subscribes)) return
- for (const url in subscribes) {
- const cb = subscribes[url]
- client.subscribe(url, (msg) => {
- let body = get(msg, 'body')
- if (body) body = JSON.parse(body)
- cb(body)
- })
- }
- }
- client.onStompError = (res) => {
- console.log('connect error')
- console.log(res)
- }
- client.activate()
- return client
- }
- export { initClient }
|