一、背景
最近项目需要在Web端中后台应用中作为消费者连接RabbitMQ,以动态接收业务系统生成的最新数据。
RabbitMQ官方有nodejs库(http://www.rabbitmq.com/tutorials/tutorial-one-javascript.html),但经测试该库只能在nodejs服务器环境使用,无法在Web浏览器端使用。
二、使用方法
要在Web端实现连接RabbitMQ,可利用Stomp协议。
服务器端
- 安装RabbitMQ
- 开启stomp相关的插件:
#添加stomp相关的插件
[root@hadoop1 ~]# rabbitmq-plugins enable rabbitmq_web_stomp rabbitmq_stomp rabbitmq_web_stomp_examples
The following plugins have been configured:
rabbitmq_management
rabbitmq_management_agent
rabbitmq_stomp
rabbitmq_web_dispatch
rabbitmq_web_stomp
rabbitmq_web_stomp_examples
Applying plugin configuration to rabbit@hadoop1...
The following plugins have been enabled:
rabbitmq_stomp
rabbitmq_web_stomp
rabbitmq_web_stomp_examples
started 3 plugins.
#重启服务
[root@hadoop1 ~]# rabbitmqctl stop_app
Stopping rabbit application on node rabbit@hadoop1 ...
[root@hadoop1 ~]# rabbitmqctl start_app
Starting node rabbit@hadoop1 ...
completed with 6 plugins.
#查看集群状态,有使用集群的话集群中的所有服务器都要添加插件
[root@hadoop1 ~]# rabbitmqctl cluster_status
Cluster status of node rabbit@hadoop1 ...
[{nodes,[{disc,[rabbit@hadoop1,rabbit@hadoop2]}]},
{running_nodes,[rabbit@hadoop2,rabbit@hadoop1]},
{cluster_name,<<"KaLian_rabbitmq_cluster">>},
{partitions,[]},
{alarms,[{rabbit@hadoop2,[]},{rabbit@hadoop1,[]}]}]
- 其他
插件添加成功后,可打开服务的15670端口查看调用示例(rabbitmq_web_stomp_examples),例如:http://localhost:15670/
stomp服务端口则为15674
Web端
- 引入
stompjs.js
库:
- https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js
- 从npm中加载
npm install stompjs --save
- 调用示例代码:
// 初始化 ws 对象
if (location.search == '?ws') {
var ws = new WebSocket('ws://localhost:15674/ws');
} else {
var ws = new SockJS('http://localhost:15674/stomp');
}
// 获得Stomp client对象
var client = Stomp.over(ws);
// SockJS does not support heart-beat: disable heart-beats
client.heartbeat.outgoing = 0;
client.heartbeat.incoming = 0;
client.debug = pipe('#second');
// 定义连接成功回调函数
var on_connect = function(x) {
//data.body是接收到的数据
client.subscribe("/queue/default", function(data) {
var msg = data.body;
alert("收到数据:" + msg);
});
};
// 定义错误时回调函数
var on_error = function() {
console.log('error');
};
// 连接RabbitMQ
client.connect('guest', 'guest', on_connect, on_error, '/');
console.log(">>>连接上http://localhost:15674");
整个连接过程分为以下步骤:
- 初始化websocket对象
- 构造stomp client
- 定义连接成功的回调函数
- 定义连接错误时的回调函数
- 连接RabbitMQ