WSO2 Message Broker supports AMQP protocol 0-9-1. If you need to use Node.js client to publish/subscribe to Message Broker this can be done with using any compatible Node.js AMQP 0-9-1 Client Library. Some of the examples
i found are,
- amqp.node : https://github.com/squaremo/amqp.node
- node-amqp : https://github.com/postwait/node-amqp
First of all we need to install Node.js if we haven't done it yet. The following page explains how to install Node.js in Ubuntu.
$ sudo apt-get install python-software-properties python g++ make
$ sudo add-apt-repository ppa:chris-lea/node.js
$ sudo apt-get update
$ sudo apt-get install nodejs
Then add 'amqplib' module to get enable the functions in 'node.amqp' library.
$ npm install amqplib
The following sample code, written using amqp.node library can be
used now as a NodeJS client to publish or receive messages from WSO2 Message
Broker. You have to use the format
amqp://{username}:{password}@{hostname}:{port}
to establish a connection with Message Broker. All messages will be sent as byte messages but can be received as text.
'amqp.node' library provide a rich API which can be used to other Queue operations MB too.
A Sample Node.js Queue Publisher for WSO2 MB
var queuename = 'MyQueue'; var openConn = require('amqplib').connect('amqp://admin:admin@localhost:5672'); // amqp://{username}:{password}@{hostname}:{port} is default AMQP connection URL of WSO2 MB openConn.then(function(conn) { var ok = conn.createChannel(); ok = ok.then(function(channel) { channel.assertQueue(queuename); channel.sendToQueue(queuename, new Buffer('New Message')); }); return ok; }).then(null, console.warn);
A Sample Node.js Queue Consumer for WSO2 MB
var queuename = 'MyQueue'; var openConn = require('amqplib').connect('amqp://admin:admin@localhost:5672'); // amqp://{username}:{password}@{hostname}:{port} is default AMQP connection URL of WSO2 MB openConn.then(function(conn) { var ok = conn.createChannel(); ok = ok.then(function(channel) { channel.assertQueue(queuename); channel.consume(queuename, function(msg) { console.log(msg.content.toString()); channel.ack(msg); }); }); return ok; }).then(null, console.warn);