实时推送消息(rabbitmq+vue实现stomp协议消息推送)

最近公司项目用到实时推送消息,所以把方法附上,各位有不同见解的留言。现在代码附上:

index.html页面内引入js

<script type="text/javascript" src="/static/sockjs.min.js" charset="utf-8"></script>
<script type="text/javascript" src="/static/webstomp.min.js" charset="utf-8"></script>

在utils内新建sysconstant.js(对参数的配置)

export const MQ_PROTOCOL = 'ws'     //连接协议
export const MQ_IP = '192.168.2.2'  //ip
export const MQ_PORT = '15674'      //端口
export const MQ_ADDRESS = 'ws'  
export const MQ_ACCOUNT = 'admin'   //账号
export const MQ_PASSWORD = 'admin'  //密码
export const MQ_SUBSCRIPT = '/exchange/school_inout/school_inout_routingkey' //订阅地址

在页面中使用

import { MQ_PROTOCOL, MQ_IP, MQ_PORT, MQ_ADDRESS, MQ_ACCOUNT, MQ_PASSWORD, MQ_SUBSCRIPT } from '../../utils/sysconstant';

export default{
    data (){
        return {
            address: null, //连接地址
            client: null,
            subscribes: {},
        }
    },
    beforeDestroy(){
        this.disconnect();
    },
    mounted(){
        let vm = this;
        vm.address = MQ_PROTOCOL + '://' + MQ_IP + ':' + MQ_PORT + '/' + MQ_ADDRESS;
        vm.connect();
    },
    methods:{
        //连接
        connect() {
            let vm = this;
            vm.client = webstomp.client(vm.address);
            vm.client.connect(MQ_ACCOUNT, MQ_PASSWORD, (e) => {
                // console.info('连接成功!');
                vm.subscribe();
            }, (e) => {
                // console.info('连接失败!')
            })
        },

        //断开连接
        disconnect(){
            let vm = this;
            if(vm.client && vm.client.connected) {
                vm.client.disconnect( () => {
                    // vm.unsubscribe();
                    vm.subscribes = {};
                    console.info('断开连接!')
                })
            }
        },

        //订阅
        subscribe() {
            let vm = this;
            if(!vm.client) {
                console.info('暂未连接')
                return;
            };
            if(!vm.client.connected) {
                console.info('暂未连接')
                return;
            } 
            if (vm.subscribes[MQ_SUBSCRIPT]){
                console.info('已经订阅了')
                return;
            }
            vm.subscribes[MQ_SUBSCRIPT] = vm.client.subscribe(MQ_SUBSCRIPT,  (e) => {
                //处理数据
                console.info(JSON.parse(e.body))
            });
        },

        //取消订阅
        unsubscribe() {
            let vm = this;
            if (vm.subscribes[MQ_SUBSCRIPT]){
                vm.subscribes[MQ_SUBSCRIPT].unsubscribe();
                delete vm.subscribes[MQ_SUBSCRIPT];
            }
        },
    }
}

当退出当前页面时会断开连接,此时不需要执行取消订阅unsubscribe()函数,另附上两个js源码:

sockjs.min.js

/* sockjs-client v1.1.5 | http://sockjs.org | MIT license */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.SockJS=t()}}(function(){var t;return function(){function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[s]={exports:{}};e[s][0].call(c.exports,function(t){return i(e[s][1][t]||t)},c,c.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}return t}()({1:[function(t,e,n){(function(n){"use strict";var r=t("./transport-list");e.exports=t("./main")(r),"_sockjs_onload"in n&&setTimeout(n._sockjs_onload,1)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./main":14,"./transport-list":16}],2:[function(t,e,n){"use strict";function r(){o.call(this),this.initEvent("close",!1,!1),this.wasClean=!1,this.code=0,this.reason=""}var i=t("inherits"),o=t("./event");i(r,o),e.exports=r},{"./event":4,"inherits":54}],3:[function(t,e,n){"use strict";function r(){o.call(this)}var i=t("inherits"),o=t("./eventtarget");i(r,o),r.prototype.removeAllListeners=function(t){t?delete this._listeners[t]:this._listeners={}},r.prototype.once=function(t,e){function n(){r.removeListener(t,n),i||(i=!0,e.apply(this,arguments))}var r=this,i=!1;this.on(t,n)},r.prototype.emit=function(){var t=arguments[0],e=this._listeners[t];if(e){for(var n=arguments.length,r=new Array(n-1),i=1;i<n;i++)r[i-1]=arguments[i];for(var o=0;o<e.length;o++)e[o].apply(this,r)}},r.prototype.on=r.prototype.addListener=o.prototype.addEventListener,r.prototype.removeListener=o.prototype.removeEventListener,e.exports.EventEmitter=r},{"./eventtarget":5,"inherits":54}],4:[function(t,e,n){"use strict";function r(t){this.type=t}r.prototype.initEvent=function(t,e,n){return this.type=t,this.bubbles=e,this.cancelable=n,this.timeStamp=+new Date,this},r.prototype.stopPropagation=function(){},r.prototype.preventDefault=function(){},r.CAPTURING_PHASE=1,r.AT_TARGET=2,r.BUBBLING_PHASE=3,e.exports=r},{}],5:[function(t,e,n){"use strict";function r(){this._listeners={}}r.prototype.addEventListener=function(t,e){t in this._listeners||(this._listeners[t]=[]);var n=this._listeners[t];-1===n.indexOf(e)&&(n=n.concat([e])),this._listeners[t]=n},r.prototype.removeEventListener=function(t,e){var n=this._listeners[t];if(n){var r=n.indexOf(e);return-1!==r?void(n.length>1?this._listeners[t]=n.slice(0,r).concat(n.slice(r+1)):delete this._listeners[t]):void 0}},r.prototype.dispatchEvent=function(){var t=arguments[0],e=t.type,n=1===arguments.length?[t]:Array.apply(null,arguments);if(this["on"+e]&&this["on"+e].apply(this,n),e in this._listeners)for(var r=this._listeners[e],i=0;i<r.length;i++)r[i].apply(this,n)},e.exports=r},{}],6:[function(t,e,n){"use strict";function r(t){o.call(this),this.initEvent("message",!1,!1),this.data=t}var i=t("inherits"),o=t("./event");i(r,o),e.exports=r},{"./event":4,"inherits":54}],7:[function(t,e,n){"use strict";function r(t){this._transport=t,t.on("message",this._transportMessage.bind(this)),t.on("close",this._transportClose.bind(this))}var i=t("json3"),o=t("./utils/iframe");r.prototype._transportClose=function(t,e){o.postMessage("c",i.stringify([t,e]))},r.prototype._transportMessage=function(t){o.postMessage("t",t)},r.prototype._send=function(t){this._transport.send(t)},r.prototype._close=function(){this._transport.close(),this._transport.removeAllListeners()},e.exports=r},{"./utils/iframe":47,"json3":55}],8:[function(t,e,n){"use strict";var r=t("./utils/url"),i=t("./utils/event"),o=t("json3"),s=t("./facade"),a=t("./info-iframe-receiver"),l=t("./utils/iframe"),u=t("./location");e.exports=function(t,e){var n={};e.forEach(function(t){t.facadeTransport&&(n[t.facadeTransport.transportName]=t.facadeTransport)}),n[a.transportName]=a;var c;t.bootstrap_iframe=function(){var e;l.currentWindowId=u.hash.slice(1);var a=function(i){if(i.source===parent&&(void 0===c&&(c=i.origin),i.origin===c)){var a;try{a=o.parse(i.data)}catch(t){return void i.data}if(a.windowId===l.currentWindowId)switch(a.type){case"s":var f;try{f=o.parse(a.data)}catch(t){a.data;break}var h=f[0],d=f[1],p=f[2],v=f[3];if(h!==t.version)throw new Error('Incompatible SockJS! Main site uses: "'+h+'", the iframe: "'+t.version+'".');if(!r.isOriginEqual(p,u.href)||!r.isOriginEqual(v,u.href))throw new Error("Can't connect to different domain from within an iframe. ("+u.href+", "+p+", "+v+")");e=new s(new n[d](p,v));break;case"m":e._send(a.data);break;case"c":e&&e._close(),e=null}}};i.attachEvent("message",a),l.postMessage("s")}}},{"./facade":7,"./info-iframe-receiver":10,"./location":13,"./utils/event":46,"./utils/iframe":47,"./utils/url":52,"debug":void 0,"json3":55}],9:[function(t,e,n){"use strict";function r(t,e){i.call(this);var n=this,r=+new Date;this.xo=new e("GET",t),this.xo.once("finish",function(t,e){var i,o;if(200===t){if(o=+new Date-r,e)try{i=s.parse(e)}catch(t){}a.isObject(i)||(i={})}n.emit("finish",i,o),n.removeAllListeners()})}var i=t("events").EventEmitter,o=t("inherits"),s=t("json3"),a=t("./utils/object");o(r,i),r.prototype.close=function(){this.removeAllListeners(),this.xo.close()},e.exports=r},{"./utils/object":49,"debug":void 0,"events":3,"inherits":54,"json3":55}],10:[function(t,e,n){"use strict";function r(t){var e=this;o.call(this),this.ir=new l(t,a),this.ir.once("finish",function(t,n){e.ir=null,e.emit("message",s.stringify([t,n]))})}var i=t("inherits"),o=t("events").EventEmitter,s=t("json3"),a=t("./transport/sender/xhr-local"),l=t("./info-ajax");i(r,o),r.transportName="iframe-info-receiver",r.prototype.close=function(){this.ir&&(this.ir.close(),this.ir=null),this.removeAllListeners()},e.exports=r},{"./info-ajax":9,"./transport/sender/xhr-local":37,"events":3,"inherits":54,"json3":55}],11:[function(t,e,n){(function(n){"use strict";function r(t,e){var r=this;i.call(this);var o=function(){var n=r.ifr=new l(u.transportName,e,t);n.once("message",function(t){if(t){var e;try{e=s.parse(t)}catch(t){return r.emit("finish"),void r.close()}var n=e[0],i=e[1];r.emit("finish",n,i)}r.close()}),n.once("close",function(){r.emit("finish"),r.close()})};n.document.body?o():a.attachEvent("load",o)}var i=t("events").EventEmitter,o=t("inherits"),s=t("json3"),a=t("./utils/event"),l=t("./transport/iframe"),u=t("./info-iframe-receiver");o(r,i),r.enabled=function(){return l.enabled()},r.prototype.close=function(){this.ifr&&this.ifr.close(),this.removeAllListeners(),this.ifr=null},e.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./info-iframe-receiver":10,"./transport/iframe":22,"./utils/event":46,"debug":void 0,"events":3,"inherits":54,"json3":55}],12:[function(t,e,n){"use strict";function r(t,e){var n=this;i.call(this),setTimeout(function(){n.doXhr(t,e)},0)}var i=t("events").EventEmitter,o=t("inherits"),s=t("./utils/url"),a=t("./transport/sender/xdr"),l=t("./transport/sender/xhr-cors"),u=t("./transport/sender/xhr-local"),c=t("./transport/sender/xhr-fake"),f=t("./info-iframe"),h=t("./info-ajax");o(r,i),r._getReceiver=function(t,e,n){return n.sameOrigin?new h(e,u):l.enabled?new h(e,l):a.enabled&&n.sameScheme?new h(e,a):f.enabled()?new f(t,e):new h(e,c)},r.prototype.doXhr=function(t,e){var n=this,i=s.addPath(t,"/info");this.xo=r._getReceiver(t,i,e),this.timeoutRef=setTimeout(function(){n._cleanup(!1),n.emit("finish")},r.timeout),this.xo.once("finish",function(t,e){n._cleanup(!0),n.emit("finish",t,e)})},r.prototype._cleanup=function(t){clearTimeout(this.timeoutRef),this.timeoutRef=null,!t&&this.xo&&this.xo.close(),this.xo=null},r.prototype.close=function(){this.removeAllListeners(),this._cleanup(!1)},r.timeout=8e3,e.exports=r},{"./info-ajax":9,"./info-iframe":11,"./transport/sender/xdr":34,"./transport/sender/xhr-cors":35,"./transport/sender/xhr-fake":36,"./transport/sender/xhr-local":37,"./utils/url":52,"debug":void 0,"events":3,"inherits":54}],13:[function(t,e,n){(function(t){"use strict";e.exports=t.location||{origin:"http://localhost:80",protocol:"http:",host:"localhost",port:80,href:"http://localhost/",hash:""}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],14:[function(t,e,n){(function(n){"use strict";function r(t,e,n){if(!(this instanceof r))return new r(t,e,n);if(arguments.length<1)throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");y.call(this),this.readyState=r.CONNECTING,this.extensions="",this.protocol="",n=n||{},n.protocols_whitelist&&m.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead."),this._transportsWhitelist=n.transports,this._transportOptions=n.transportOptions||{};var i=n.sessionId||8;if("function"==typeof i)this._generateSessionId=i;else{if("number"!=typeof i)throw new TypeError("If sessionId is used in the options, it needs to be a number or a function.");this._generateSessionId=function(){return u.string(i)}}this._server=n.server||u.numberString(1e3);var o=new s(t);if(!o.host||!o.protocol)throw new SyntaxError("The URL '"+t+"' is invalid");if(o.hash)throw new SyntaxError("The URL must not contain a fragment");if("http:"!==o.protocol&&"https:"!==o.protocol)throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '"+o.protocol+"' is not allowed.");var a="https:"===o.protocol;if("https:"===g.protocol&&!a)throw new Error("SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS");e?Array.isArray(e)||(e=[e]):e=[];var l=e.sort();l.forEach(function(t,e){if(!t)throw new SyntaxError("The protocols entry '"+t+"' is invalid.");if(e<l.length-1&&t===l[e+1])throw new SyntaxError("The protocols entry '"+t+"' is duplicated.")});var c=f.getOrigin(g.href);this._origin=c?c.toLowerCase():null,o.set("pathname",o.pathname.replace(/\/+$/,"")),this.url=o.href,this.url,this._urlInfo={nullOrigin:!v.hasDomain(),sameOrigin:f.isOriginEqual(this.url,g.href),sameScheme:f.isSchemeEqual(this.url,g.href)},this._ir=new _(this.url,this._urlInfo),this._ir.once("finish",this._receiveInfo.bind(this))}function i(t){return 1e3===t||t>=3e3&&t<=4999}t("./shims");var o,s=t("url-parse"),a=t("inherits"),l=t("json3"),u=t("./utils/random"),c=t("./utils/escape"),f=t("./utils/url"),h=t("./utils/event"),d=t("./utils/transport"),p=t("./utils/object"),v=t("./utils/browser"),m=t("./utils/log"),b=t("./event/event"),y=t("./event/eventtarget"),g=t("./location"),w=t("./event/close"),x=t("./event/trans-message"),_=t("./info-receiver");a(r,y),r.prototype.close=function(t,e){if(t&&!i(t))throw new Error("InvalidAccessError: Invalid code");if(e&&e.length>123)throw new SyntaxError("reason argument has an invalid length");if(this.readyState!==r.CLOSING&&this.readyState!==r.CLOSED){this._close(t||1e3,e||"Normal closure",!0)}},r.prototype.send=function(t){if("string"!=typeof t&&(t=""+t),this.readyState===r.CONNECTING)throw new Error("InvalidStateError: The connection has not been established yet");this.readyState===r.OPEN&&this._transport.send(c.quote(t))},r.version=t("./version"),r.CONNECTING=0,r.OPEN=1,r.CLOSING=2,r.CLOSED=3,r.prototype._receiveInfo=function(t,e){if(this._ir=null,!t)return void this._close(1002,"Cannot connect to server");this._rto=this.countRTO(e),this._transUrl=t.base_url?t.base_url:this.url,t=p.extend(t,this._urlInfo);var n=o.filterToEnabled(this._transportsWhitelist,t);this._transports=n.main,this._transports.length,this._connect()},r.prototype._connect=function(){for(var t=this._transports.shift();t;t=this._transports.shift()){if(t.transportName,t.needBody&&(!n.document.body||void 0!==n.document.readyState&&"complete"!==n.document.readyState&&"interactive"!==n.document.readyState))return this._transports.unshift(t),void h.attachEvent("load",this._connect.bind(this));var e=this._rto*t.roundTrips||5e3;this._transportTimeoutId=setTimeout(this._transportTimeout.bind(this),e);var r=f.addPath(this._transUrl,"/"+this._server+"/"+this._generateSessionId()),i=this._transportOptions[t.transportName],o=new t(r,this._transUrl,i);return o.on("message",this._transportMessage.bind(this)),o.once("close",this._transportClose.bind(this)),o.transportName=t.transportName,void(this._transport=o)}this._close(2e3,"All transports failed",!1)},r.prototype._transportTimeout=function(){this.readyState===r.CONNECTING&&(this._transport&&this._transport.close(),this._t
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值