版權宣告:本文為LeeKwen的原創文章,請聯絡微信@leekwenty後轉載。 https://blog.csdn.net/leekwen/article/details/38896931
一、測試條件:
1.1、ubuntu伺服器平臺
首先,安裝好Nodejs及Rabbitmq訊息伺服器(Ubuntu下的Rabbitmq訊息伺服器的安裝,可以直接使用此指令碼Rabbitmq-install.sh)。
Rabbitmq-install.sh 指令碼程式碼如下:
#!/bin/sh
echo "deb http://www.rabbitmq.com/debian/ testing main" >> /etc/apt/sources.list
wget -c http://www.rabbitmq.com/rabbitmq-signing-key-public.asc
apt-key add rabbitmq-signing-key-public.asc
apt-get update
apt-get install -y rabbitmq-server g++ make
rm -fr rabbitmq-signing-key-public.asc
rabbitmq-plugins enable mochiweb webmachine rabbitmq_web_dispatch amqp_client rabbitmq_management_agent rabbitmq_management
rabbitmqctl delete_user guest
rabbitmqctl add_user admin admin
rabbitmqctl set_permissions -p "/" admin ".*" ".*" ".*"
rabbitmqctl set_user_tags admin administrator
/etc/init.d/rabbitmq-server restart
假定伺服器已經安裝好上述兩種服務,而且訊息伺服器的使用者名稱/密碼均為admin/admin.
1.2、安裝nodejs與Rabbitmq訊息伺服器互動所需的node-amqp模組。
執行如下命令:
[leekwen@ubuntu ~] mkdir node-amqp; cd node-amqp
[leekwen@ubuntu node-amqp]$ npm install rabbitmq; npm install amqp
2.1、node-amqp所在的github地址(含API說明)
2.2、使用node-amqp的測試例項
測試程式碼如下:
/*
* Install Rabbitmq Server
* Install nodejs && nmp
* Run those commands:
* [leekwen@ubuntu ~] mkdir node-amqp; cd node-amqp
* [leekwen@ubuntu node-amqp]$ npm install rabbitmq
* [leekwen@ubuntu node-amqp]$ npm install amqp
*/
var amqp = require('amqp');
var connection = amqp.createConnection({url: "amqp://admin:admin@127.0.0.1:5672"});
connection.on('ready', function () {
var callbackCalled = false;
exchange = connection.exchange('exchange_name', {type: 'direct',autoDelete:false});
connection.queue("queue_name",{autoDelete:false}, function(queue){
queue.bind('exchange_name','queue_name', function() {
exchange.publish('queue_name', 'this is message is testing ......');
callbackCalled = true;
setTimeout(function() {
console.log("Single queue bind callback succeeded");
//exchange.destroy();
//queue.destroy();
connection.end();
connection.destroy();
}, 5000);
});
queue.subscribe(function (message) {
console.log('At 5 second recieved message is:'+ message.data);
});
});
});
具體使用請參照node-amqp的相關API。