- STOMP plugin
Stomp是一个简单的消息文本协议(不重点介绍,没仔细研究过)。RabbitMQ中STOMP plugin的集成,实现了由浏览器通过WebSocket协议访问消息队列,SockJS作为后备(旧版的浏览器不支持WebSocket协议)
启用stomp plugin命令代码
- rabbitmq-plugins enable rabbitmq_web_stomp
- rabbitmq-plugins enable rabbitmq_web_stomp_examples
通过链接:http://127.0.0.1:15670/web-stomp-examples可以访问演示样例,实际上没法用,因为引用的jquery.min.js是google的资源。
关键代码
- var mqStompUrl="http://192.168.174.131:15674/stomp";
- var ws = new SockJS(mqStompUrl);//使用socket
- //var ws = new WebSocket("ws://192.168.174.131:15674/ws");//使用websocket
- var client = Stomp.over(ws);
- // SockJS does not support heart-beat: disable heart-beats
- client.heartbeat.incoming = 0;
- client.heartbeat.outgoing = 0;
- client.debug = function(e) {
- console.log(e);
- };
- // default receive callback to get message from temporary queues
- client.onreceive = function(m) {
- console.log(m)
- }
- var on_connect = function(x) {
- id = client.subscribe("/queue/hehe",function(m) {
- //...
- }});
- };
- var on_error = function() {
- console.log('error');
- };
- client.connect('sheungxin', '123456', on_connect, on_error, '/');
- client.send("/queue/hehe",{"content-type":"text/plain"}, text);
使用websocket时报以下错误:failed: Error during WebSocket handshake: Unexpected response code: 404,暂时未找到原因
可参考:http://www.rabbitmq.com/web-stomp.html
- 简单总结
/queue/queuename:使用默认转发器订阅/发布消息,默认由stomp自动创建一个持久化队列
/amq/queue/queuename:与/queue/queuename的区别在于队列不由stomp自动进行创建,队列不存在失败
/topic/routing_key:通过amq.topic转发器订阅/发布消息,订阅时默认创建一个临时队列,通过routing_key与topic进行绑定
/temp-queue/xxx:创建一个临时队列(只能在headers中的属性reply-to中使用),可用于发送消息后通过临时队列接收回复消息,接收通过client.onreceive
/exchange/exchangename/[routing_key]:通过转发器订阅/发布消息,转发器需要手动创建
client.subscribe(destination,callback,headers) :订阅消息
client.send(destination,headers,body):发布消息
client.unsubscribe(id):取消订阅,id为订阅时返回的编号
client.onreceive:默认接收回调从临时队列获取消息
- Queue Properties的支持
需要版本的支持,3.6.0以后大多都可以支持,具体具体参考:http://www.rabbitmq.com/stomp.html
- 中文消息无法发送问题
中文消息,stomp协议存在编码的问题,发送不出去,会报错关闭掉。可以对中文消息进行encodeURI(data),接收消息时decodeURI(d.body)。官网文章中提供,消息编码必须为UTF-8。