var amqp = require('amqp'); function rabbitUrl() { if (process.env.VCAP_SERVICES) { conf = JSON.parse(process.env.VCAP_SERVICES); return conf['rabbitmq-2.4'][0].credentials.url; } else { return "amqp://guest:
@localhost"; } } var config = { exchangeName:'404hound', queueName:'ping.job' }; function init() { var conn = createConnection(); conn.on('ready', function () { console.log("Starting..."); conn.queue(config.queueName, {durable:true, exclusive:true}, function (q) { q.bind(config.exchangeName, '#'); //subscribe to all messages. q.subscribe(function (msg) { console.log(msg); }); }); }); } function publish(msg, conn) { if (conn === undefined) { conn = createConnection(); } conn.on('ready', function () { console.log("Sending message..."); conn.publish(config.queueName, {body:msg}); }); } function createConnection() { return amqp.createConnection({url:rabbitUrl()}, {defaultExchangeName:config.exchangeName}); } module.exports.init = init; module.exports.publish = publish; module.exports.createConnection = createConnection;
The first function defines the url value. Notice that we are saying if it's defined by CloudFoundry, then we use it...otherwise we use our local config.
We then define an init() function that will create the connection with the exchange it we want. After that we wait until the connection is ready. Once it's ready we can then bind it to the messages we want to read. A '#' means we want to subscribe to all messages. Then we define what should happen when a message comes in. In this simply case we just log it.
The second part of this is the publish function. There are times where we don't want to create a connection for each message we're sending, so we can opt to pass in the connection. Again it's simple as publishing to the queue you want to send to.
Here's some sample output:
Starting... Sending message... { body: 'hello' }
Notice my code above differs from the sample code from CloudFoundry...after reading the ampq plugin for Node I realized that the guys at CF are using a deprecated way to sending/receiving messages.
Note #1: You will need to create your exchange on RabbitMQ first. In my case I created the exchange 404hound. You can also use the ampq plugin to create the exchange.
No comments:
Post a Comment