node使用消息队列RabbitMQ一

基础发布和订阅

消息队列RabbitMQ使用

1 安装RabbitMQ服务器

  • 安装erlang服务javascript

    下载地址 http://www.erlang.org/downloadshtml

  • 安装RabbitMQjava

    下载地址 http://www.rabbitmq.com/download.htmlnode

    windows上安装完成以后,rabbitmq将做为系统服务自启动。(使用rabbitmq-plugins.bat enable rabbitmq_management能够开启网页管理界面)git

2 安装RabbitMQ客户端

npm install amqp

3 发布与订阅

使用流程

  • 创建发布者

connection.publish(routingKey, body, options, callback)
将消息发送发到routingKeygithub

var amqp = require('amqp');
var connection = amqp.createConnection();
// add this for better debuging
connection.on('error', function(e) {
console.log("Error from amqp: ", e);
});
// Wait for connection to become established.
connection.on('ready', function () {
// Use the default 'amq.topic' exchange
console.log("connected to----"+ connection.serverProperties.product);
connection.publish("my-queue",{hello:'world'});
});
  • 创建订阅者

connection.queue(name[, options][, openCallback])
经过队列名来接收消息,此处的name对应routingKeyweb

注意

队列名必定要匹配npm

var amqp = require('amqp');
var connection = amqp.createConnection();
// add this for better debuging
connection.on('error', function(e) {
console.log("Error from amqp: ", e);
});
// Wait for connection to become established.
connection.on('ready', function () {
// Use the default 'amq.topic' exchange
connection.queue('my-queue', function (q) {
// Catch all messages
q.bind('#');
// Receive messages
q.subscribe(function (message) {
// Print messages to stdout
console.log(message);
});
});
});

分别运行发布者和订阅者,能够看到订阅者接受到发布的消息。windows

4 使用exchange

 exchange是负责接收消息,并把他们传递给绑定的队列的实体。经过使用exchange,能够在一台服务器上隔离不一样的队列。服务器

  • 发布者的更改

发布者的是在链接中创建exchange,在callback中绑定exchange和queue,而后使用exchange来发布queue的消息

注意

exchange使用完整的函数形式(指明option),否则exchange不会运行!!!

connection.exchange("my-exchange", options={type:'fanout'}, function(exchange) {
console.log("***************");
var q = connection.queue("my-queue");
q.bind(exchange,'my-queue');
exchange.publish('my-queue',{hello:'world'});
});
  • 订阅者的更改

订阅者的更改只是将默认的绑定更改成指定的exchange

connection.queue('my-queue', function (q) {
// Receive messages
q.bind('my-exchange','#');
q.subscribe(function (message) {
// Print messages to stdout
console.log(message);
});
});

reference

https://www.npmjs.com/package/amqp#connectionpublishroutingkey-body-options-callback

https://github.com/rabbitmq/rabbitmq-tutorials/tree/master/javascript-nodejs

https://thiscouldbebetter.wordpress.com/2013/06/12/using-message-queues-in-javascript-with-node-js-and-rabbitmq/

http://stackoverflow.com/questions/10620976/rabbitmq-amqp-single-queue-multiple-consumers-for-same-message

相关文章
相关标签/搜索