当Node.js遇上RabbitMQ

RabbitMQ安装

以Mac安装为例

官网:http://www.rabbitmq.com/

> brew install rabbitmq

RabbitMQ启动

启动脚本:

> /usr/local/sbin/rabbitmq-server

RabbitMQ管理界面

参考:http://www.rabbitmq.com/management.html

启动指令:

> /usr/local/sbin/rabbitmq-plugins enable rabbitmq_management

可以通过http://{server-name}:15672访问
Fos-m8VGyJ9mwKVLYF5BIn4bTtHx

为了使用Web UI,还需要进行用户授权,初次登录可以使用guest/guest用户进行授权。Admin->Users->Add user
FtOWgsuD7qsOCYkzgs_7A5einX2g

RabbitMQ配置

参考文档:http://www.rabbitmq.com/configure.html#customise-general-unix-environment
可以下载到样例配置文档。

Node.js + RabbitMQ

这里我们使用Node.js的AMQP客户端,demo代码如下:

消费者consumer.js

const amqp = require('amqp');

//连接RabbitMQ
const connection = amqp.createConnection({
    url: "amqp://name:password@127.0.0.1:5672"
});

let mqStop = false;  
connection.on('ready', () => {
    console.log('RabbitMQ消费者已经连接');
    //建立一个队列
    connection.queue('myQueue', { 
        durable: true,
        autoDelete: false
    }, (queue) => {  
        console.log('队列「 ' + queue.name + '」已开启!'); 
        //订阅队列(消费者)
        queue.subscribe((message, header, deliveryInfo) => {  
            if (message.data) {  
                const messageText = message.data.toString();
                console.log(messageText);
                //当接收到exit消息时,退出程序
                if (messageText === "exit") {
                    mqStop = true;
                } 
            }  
        });  
    });
});

//保持执行
const keepItRunning = () => {
    if (!mqStop) {
        setTimeout(keepItRunning, 1000);
    } else {
        connection.end();
    }
}
keepItRunning();

生产者producer.js

const amqp = require('amqp');

//连接RabbitMQ
const connection = amqp.createConnection({
    url: "amqp://name:password@127.0.0.1:5672"
});
connection.on('ready', () => {
    console.log('RabbitMQ生产者已经连接');
    for(let i = 0; i < 1000; i++) {
        //发布消息(生产者)
        connection.publish('myQueue', `我是第${i}条消息`);
    }
    connection.publish('myQueue', 'exit');
});