2015-12-16 22:57:58 +08:00
|
|
|
'use strict';
|
|
|
|
|
2016-10-12 00:41:59 +08:00
|
|
|
var Channel = require('./channel');
|
2016-10-12 00:28:46 +08:00
|
|
|
var debug = require('./../util/debug')('pubsub:subscriber');
|
|
|
|
var error = require('./../util/debug')('pubsub:subscriber:error');
|
2016-07-07 16:44:17 +08:00
|
|
|
|
2019-12-24 01:19:08 +08:00
|
|
|
function JobSubscriber (pool) {
|
2016-07-07 20:14:46 +08:00
|
|
|
this.pool = pool;
|
2015-12-16 22:57:58 +08:00
|
|
|
}
|
|
|
|
|
2016-04-05 02:00:18 +08:00
|
|
|
module.exports = JobSubscriber;
|
|
|
|
|
2016-10-12 01:59:11 +08:00
|
|
|
JobSubscriber.prototype.subscribe = function (onJobHandler, callback) {
|
2016-03-31 23:37:35 +08:00
|
|
|
var self = this;
|
|
|
|
|
2020-05-18 17:32:41 +08:00
|
|
|
self.pool.acquire(Channel.DB)
|
|
|
|
.then(client => {
|
|
|
|
self.client = client;
|
|
|
|
client.removeAllListeners('message');
|
|
|
|
client.unsubscribe(Channel.NAME);
|
|
|
|
client.subscribe(Channel.NAME);
|
|
|
|
client.on('message', function (channel, user) {
|
|
|
|
debug('message received in channel=%s from user=%s', channel, user);
|
|
|
|
onJobHandler(user);
|
|
|
|
});
|
|
|
|
|
|
|
|
client.on('error', function () {
|
|
|
|
self.unsubscribe();
|
|
|
|
self.pool.release(Channel.DB, client)
|
|
|
|
.catch(err => error('Error releasing redis client: ' + err.message));
|
|
|
|
self.subscribe(onJobHandler);
|
|
|
|
});
|
|
|
|
|
2017-03-31 20:30:33 +08:00
|
|
|
if (callback) {
|
2020-05-18 17:32:41 +08:00
|
|
|
callback();
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch(err => {
|
|
|
|
error('Error adquiring redis client: ' + err.message);
|
|
|
|
if (callback) {
|
|
|
|
return callback(err);
|
2017-03-31 20:30:33 +08:00
|
|
|
}
|
2016-10-12 01:45:43 +08:00
|
|
|
});
|
2015-12-16 22:57:58 +08:00
|
|
|
};
|
|
|
|
|
2016-10-12 18:29:54 +08:00
|
|
|
JobSubscriber.prototype.unsubscribe = function (callback) {
|
2016-07-07 20:14:46 +08:00
|
|
|
if (this.client && this.client.connected) {
|
2016-10-12 18:29:54 +08:00
|
|
|
this.client.unsubscribe(Channel.NAME, callback);
|
|
|
|
} else {
|
2016-10-13 03:32:29 +08:00
|
|
|
if (callback) {
|
|
|
|
return callback(null);
|
|
|
|
}
|
2016-07-07 20:14:46 +08:00
|
|
|
}
|
2015-12-23 03:12:10 +08:00
|
|
|
};
|