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

相關文章
相關標籤/搜索