-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
63 lines (56 loc) · 1.42 KB
/
index.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
'use strict';
var Redis = require('ioredis');
var debug = require('debug')('koa-redis-pool');
var poolModule = require('generic-pool');
var merge = require('merge-descriptors');
var defaultOptions = {
max: 100,
min: 1,
timeout: 30000,
log: false
};
module.exports = function(options) {
options = options || {};
if ('string' === typeof options) {
options = { url: options };
}
options = merge(defaultOptions, options);
var _redisPool = poolModule.Pool({
name : 'koa-redis-pool',
create : function(callback) {
var client;
if (options.url) {
client = new Redis(options.url);
} else {
client = new Redis(options);
}
client.once('error', function (e) {
console.error(e);
callback(e);
});
client.once('connect', function () {
callback(null, client);
});
},
destroy : function (client) {
client.end();
},
max : options.max,
min : options.min,
idleTimeoutMillis : options.timeout,
log : options.log
});
return function* redisPool(next) {
this.redis = yield _redisPool.acquire.bind(_redisPool);
if (!this.redis) this.throw('Fail to acquire one redis connection');
debug('Acquire one connection');
try {
yield next;
} catch (e) {
throw e;
} finally {
_redisPool.release(this.redis);
debug('Release one connection');
}
};
};