-
Notifications
You must be signed in to change notification settings - Fork 11
/
rabbitsender.js
67 lines (51 loc) · 1.81 KB
/
rabbitsender.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
56
57
58
59
60
61
62
63
64
65
66
67
const Amqp = require('amqplib');
class RabbitSender {
constructor(channel, config) {
this.channel = channel;
this.config = config
}
static async init(config) {
const conn = await Amqp.connect(config.connectionString);
const channel = await conn.createChannel();
channel.assertQueue('block_range', {durable: true});
channel.assertQueue('contract_row', {durable: true});
channel.assertQueue('permission_link', {durable: true});
channel.assertQueue('trace', {durable: true});
channel.assertQueue('action', {durable: true});
console.log(`Connected to ${config.connectionString}`);
const rs = new RabbitSender(channel, config);
conn.on('error', function (err) {
if (err.message !== 'Connection closing') {
console.error('[AMQP] conn error', err.message)
}
});
conn.on('close', (function () {
console.error('[AMQP] closing');
if (RabbitSender.closeHandlers && RabbitSender.closeHandlers.length){
RabbitSender.closeHandlers.forEach((h) => {
h();
});
}
}).bind(rs));
return rs
}
async send(queue_name, msg) {
if (!Buffer.isBuffer(msg)) {
msg = Buffer.from(msg)
}
return this.channel.sendToQueue(queue_name, msg)
}
async listen(queue_name, cb) {
this.channel.prefetch(1);
// await this.channel.assertQueue(queue_name, {durable: true})
this.channel.consume(queue_name, cb, {noAck: false})
}
async ack(job) {
return this.channel.ack(job)
}
async reject(job) {
return this.channel.reject(job, true)
}
}
RabbitSender.closeHandlers = [];
module.exports = RabbitSender;