-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumer.js
47 lines (43 loc) · 1.29 KB
/
consumer.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
require('dotenv').config();
const amqp = require("amqplib");
const domain = require("domain");
let exchangeName = "amq.direct";
let queueName = "testQ1";
let routingKey = "test";
//use domain module to handle reconnecting
let consumer;
const dom = domain.create();
dom.on("error", relisten);
dom.run(listen);
function listen() {
consumer = amqp.connect(process.env.RABBIT_MQ);
consumer.then((conn) => {
return conn.createChannel().then((ch) => {
ch.assertExchange(exchangeName, 'direct', {
durable: true,
autoDelete: false
});
ch.assertQueue(queueName, {
durable: true,
autoDelete: false,
exclusive: false
});
ch.bindQueue(queueName, exchangeName, routingKey);
ch.consume(queueName, (message) => {
//callback funtion on receiving messages
console.log(message.content.toString());
}, {
noAck: false
});
});
}).then(null, (err) => {
console.error("Exception handled, reconnecting...\nDetail:\n" + err);
setTimeout(listen, 5000);
});
}
function relisten() {
consumer.then((conn) => {
conn.close();
});
setTimeout(listen, 5000);
}