-
Notifications
You must be signed in to change notification settings - Fork 8
/
amqp-plus.js
108 lines (82 loc) · 2.81 KB
/
amqp-plus.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright (c) 2014, Joyent, Inc.
*/
var amqp = require('amqp');
var util = require('util');
var RECONNECT_TIMEOUT = 30000;
function Connection(connectionArgs, options) {
var self = this;
amqp.Connection.apply(this, arguments);
if (options) {
this.resource = options.resource;
this.log = options.log;
}
this.connected = false;
this.connecting = false;
this.reconnectionInterval = null;
this.reconnectTimeout = null;
self.on('ready', function () {
self.log.info('AMQP Ready');
self.connecting = false;
self.connected = true;
clearTimeout(self.reconnectTimeout);
clearInterval(self.reconnectionInterval);
self.reconnectTimeout = null;
self.reconnectionInterval = null;
});
self.on('error', function (e) {
self.connecting = false;
self.log.error(e, 'AMQP connection error');
clearTimeout(self.reconnectTimeout);
clearInterval(self.reconnectionInterval);
self.reconnectTimeout = null;
self.reconnectionInterval = null;
self.reconnectionInterval = setInterval(function () {
self.log.warn('forcing reconnect');
self.reconnect();
}, RECONNECT_TIMEOUT);
});
self.on('close', function (e) {
self.log.info('AMQP Connection close');
self.connecting = false;
self.connected = false;
clearTimeout(self.reconnectTimeout);
clearInterval(self.reconnectionInterval);
self.reconnectTimeout = null;
self.reconnectionInterval = null;
self.reconnectionInterval = setInterval(function () {
self.log.warn('forcing reconnect');
self.reconnect();
}, RECONNECT_TIMEOUT);
});
}
util.inherits(Connection, amqp.Connection);
Connection.prototype.reconnect = function () {
var self = this;
clearTimeout(self.reconnectTimeout);
clearInterval(self.reconnectionInterval);
self.reconnectTimeout = null;
self.reconnectionInterval = null;
self.connecting = true;
self.log.info('Connecting to AMQP');
self.reconnectTimeout = setTimeout(function () {
self.log.error('Timed-out waiting for AMQP ready event');
self.end();
amqp.Connection.prototype.reconnect.apply(self, arguments);
}, RECONNECT_TIMEOUT);
amqp.Connection.prototype.reconnect.apply(self, arguments);
};
function createConnection(connectionArgs, options) {
var c = new Connection(connectionArgs, options);
c.connect();
return c;
}
module.exports = {
Connection: Connection,
createConnection: createConnection
};