Try   HackMD

以 Websocket STOMP 與 rabbitmq 溝通

啟用 Web STOMP

rabbitmq-plugins enable rabbitmq_web_stomp

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

引入 js WebSocket

stomp-websocket \lib\stomp.js
Add support for receiving fragmented STOMP frames. These can orginate…

<!-- include the client library --> <script src="stomp.js"></script>

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

docker 記得把 端口 暴露

port 15672

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Sample Code

var ws = new WebSocket('ws://127.0.0.1:15674/ws'); var client = Stomp.over(ws); var on_connect = function() { console.log('connected'); }; var on_error = function() { console.log('error'); };

發送消息:

client.send('/exchange/交換機名字/路由鍵', {}, "Hello");

訂閱交換機

client.subscribe('/exchange/交換機名字/路由鍵', function(frame){}, {});

可以對 交換機內容做封裝
這邊是針對 我自己額外寫的一個 sha 根據登陸名稱來 產生 sha256
因為 假設都是同一組 queue 這樣的話,這樣 當兩個 client 同時訂閱同一個 queue 的話 會變成 queue 裡面有兩個 client 好像是 ha模式?
意味者 執行 上方 發送訊息 則 假設 queue 有兩個 client,也就是 a和 b 那麼 第一次呼叫後 則會 a收到訊息 再來就是 b 這樣循環下去
延伸閱讀 三种Exchange模式

var sha =sha256(loginName); client.subscribe('/exchange/amq.fanout/test', this.AmqpReturn, { 'x-queue-name':sha, 'durable': true });

擴展:

AmqpReturn(frame) { var obj = JSON.parse(frame.body); console.log(obj.data); }

其他參數:
除了這裡用到的參數外,還支持下面的隊列參數:

durable (aliased as persistent):持久化
auto-delete:自动删除
exclusive:独占
還額外支持 x- 參數控制死信、隊列和消息等:

x-dead-letter-exchange
x-dead-letter-routing-key
x-expires
x-message-ttl
x-max-length
x-max-length-bytes
x-overflow
x-max-priority