-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrabbitMQ_messaging.js
55 lines (39 loc) · 1.25 KB
/
rabbitMQ_messaging.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var amqp = require('amqplib/callback_api');
module.exports = rabbitMQMessages;
function rabbitMQMessages(address, callback){
//connect to RabbitMQ
amqp.connect(address, function amqpConnectCallback(err, conn){
if(err){
return callback(err);
}
//create a channel
conn.createChannel(function(err, ch){
if(err){
return callback(err);
}
ch.assertExchange('messages', 'fanout', {durable: false});
//setup a queue for receiving messages
ch.assertQueue('', {exclusive: true}, function(err, q){
if(err){
return callback(err);
}
ch.bindQueue(q.queue, 'messages', '');
var options = {
emitMessage: emitMessage,
onMessageReceived: onMessageReceived
};
//listen for messages
ch.consume(q.queue, function(msg){
options.onMessageReceived(JSON.parse(msg.content.toString()));
}, {noAck: true});
callback(null, options);
function emitMessage(message){
ch.publish('messages', '', new Buffer(JSON.stringify(message)));
}
function onMessageReceived(){
console.log('Message received. Nothing to do.');
}
});
});
});
}