公司項目要求要有消息提醒機制 , 多方面考慮用了ActiveMQ ,基本上現在主流的后台語言都沒啥問題 , php phthon java nodejs , 等等都沒問題 , 各位道友可以去查閱相關資料 , 我這里只粘貼出前端的代碼
<template> <div></div> </template> <script> import Stomp from "stompjs"; function uuid() { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return uuid; } export default { data() { return { // client: Stomp.client("ws://192.168.1.103:61614/stomp") client: null }; }, methods: { onConnected(frame) { console.log("Connected: " + frame); var topic = "/topic/charger.messageTopic"; this.client.subscribe(topic, this.responseCallback, this.onFailed); }, onFailed(frame) { console.log("Failed: " + frame); }, responseCallback(frame) { console.log("得到的消息 msg=>" + frame.body); console.log(frame) }, connect() { this.client= Stomp.client("ws://192.168.1.103:61614/stomp") var clientid = uuid(); var headers = { "login": "admin", "passcode": "admin", "client-id": clientid, // additional header }; this.client.connect(headers, this.onConnected, this.onFailed); } }, mounted() { this.connect() } }; </script>
請廣大道友注意如果直接install stompjs (中間沒點 , 別整錯了)那么在vue里面會報錯 , 因為還需要install 一下 net
var Stomp = require('./lib/stomp.js'); var StompNode = require('./lib/stomp-node.js'); module.exports = Stomp.Stomp; module.exports.overTCP = StompNode.overTCP; module.exports.overWS = StompNode.overWS;
index.js 里面引用到了這個stomp-node.js然兒這個node.js
Stomp = require('./stomp'); net = require('net'); Stomp.Stomp.setInterval = function(interval, f) { return setInterval(f, interval); };
用到了net ,
請注意箭頭函數的使用 , if你直接使用function的話會有this的指向性問題 , client里面封裝了很多原型函數 , 如果this指向調用錯誤的話這些函數都會找不到
