yw6866 发表于 2017-7-2 11:16:35

node使用消息队列RabbitMQ一

基础发布和订阅

消息队列RabbitMQ使用

1 安装RabbitMQ服务器


[*]  安装erlang服务
  下载地址 http://www.erlang.org/downloads

[*]  安装RabbitMQ
  下载地址 http://www.rabbitmq.com/download.html
  windows上安装完成之后,rabbitmq将作为系统服务自启动。(使用rabbitmq-plugins.bat enable rabbitmq_management可以开启网页管理界面)


2 安装RabbitMQ客户端

npm install amqp
3 发布与订阅

使用流程


[*]建立发布者
  connection.publish(routingKey, body, options, callback)
将消息发送发到routingKey

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对应routingKey

注意
  队列名一定要匹配

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);
      });
});
});
  分别运行发布者和订阅者,可以看到订阅者接受到发布的消息。

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

页: [1]
查看完整版本: node使用消息队列RabbitMQ一