-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathredis.js
125 lines (104 loc) · 2.87 KB
/
redis.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"use strict";
var redis = require('redis');
var debug = require('debug')('obcache');
var redisStore = {
init: function(options) {
var client ;
var prefix;
var keylen = 0;
var maxAge = (options && options.maxAge) || 60000;
var port = options.redis.port;
var host = options.redis.host;
var ropts = {};
function setKeylen(err,size) {
keylen = size;
}
if (!options || isNaN(Number(options.id)) ) {
throw new Error('Specify an integer cacheid for persistence across reboots, not ' + options.id);
}
if (options.redis.twemproxy) {
ropts.no_ready_check = true;
debug('twemproxy compat mode. stats on keys will not be available.');
}
client = redis.createClient(port, host, ropts);
client.on('error', function(err) {
debug('redis error ' + err);
});
if (!options.redis.twemproxy) {
client.select(options.id);
client.dbsize(setKeylen);
}
prefix = 'obc:' + options.id + ':' ;
var rcache = {
maxAge : maxAge,
client : client,
get : function(key, cb) {
key = prefix + key;
var ttl = this.maxAge/1000;
client.get(key, function(err, data){
var result;
if (err || !data) {
return cb(err);
}
data = data.toString();
try {
result = JSON.parse(data);
} catch (e) {
return cb(e);
}
// don't reset the ttl
//client.expire(key,ttl);
return cb(null, result);
});
},
set : function(key, val, cb){
key = prefix + key;
try {
var ttl = this.maxAge/1000;
var obj = JSON.stringify(val);
debug('setting key ' + key + ' in redis with ttl ' + ttl);
client.setex(key, ttl, obj, function(err){
if (cb) {
cb.apply(this, arguments);
}
});
} catch (err) {
if (cb) {
cb(err);
}
}
},
expire: function(key,cb) {
key = prefix + key;
client.expire(key,0,cb || function() {});
},
reset: function() {
if (options.redis.twemproxy) {
throw new Error('Reset is not possible in twemproxy compat mode');
}
client.flushdb();
},
size: function() {
return 0;
},
keycount: function() {
// this is a hack to make this function sync,
// second call will return a truer keycount
if (options.redis.twemproxy) {
return -1;
}
client.dbsize(setKeylen);
return keylen;
}
};
return rcache;
}
};
module.exports = redisStore;
(function() {
if (require.main === module) {
var store = redisStore.init({ redis: { port: 6379 }, id: 0 });
console.log('created cache ' + store);
store.keycount(console.log);
}
}());