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 发布与订阅
使用流程
- 建立发布者
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'});
});
- 建立订阅者
注意
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
- 发布者的更改
注意
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'});
});
- 订阅者的更改
connection.queue('my-queue', function (q) {
// Receive messages
q.bind('my-exchange','#');
q.subscribe(function (message) {
// Print messages to stdout
console.log(message);
});
});