api_cache.js
3.43 KB
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
import Memcached from 'memcached';
import ws from '../../lib/ws';
import _ from 'lodash';
class ApiCache {
constructor(host) {
this.host = host;
this.memcached = new Memcached(host);
}
delKey(key) {
this._log(`deleting ${key}`)
this.memcached.del(key, (err) => {
if (err) {
this._log(`deleted ${key} fail`)
} else {
this._log(`deleted ${key} success`)
}
});
}
flushAll() {
this.memcached.flush(err => {
if (err) {
this._log(`flush all fail.` + err.toString())
} else {
this._log(`flush all success`)
}
this.memcached.end();
});
}
clean(key) {
let begin = new Date();
let key1 = `apiCache:${key}`;
let key2 = `apiCache2:${key}`;
let count = 0;
this.memcached.items( ( err, result ) => {
if( err ) console.error( err );
if (result.length === 0) {
this._log('empty items')
}
// for each server...
result.forEach(itemSet => {
var keys = Object.keys( itemSet );
keys.pop(); // we don't need the "server" key, but the other indicate the slab id's
var len = keys.length;
if (keys.length === 0) {
this._log('empty item set');
}
keys.forEach(stats => {
// get a cachedump for each slabid and slab.number
this.memcached.cachedump( itemSet.server, parseInt(stats, 10), itemSet[stats].number, ( err, response ) => {
// dump the shizzle
if (response) {
if (_.isArray(response)) {
_.each(response, keyObj => {
count ++ ;
if (keyObj.key && (keyObj.key.indexOf(key1) >= 0 || keyObj.key.indexOf(key2) >= 0 || keyObj.key.indexOf(key) >= 0)) {
this.delKey(keyObj.key);
} else {
// this._log(`skip ${keyObj.key}`)
}
});
} else {
count ++;
if (response.key && (response.key.indexOf(key1) >= 0 || response.key.indexOf(key2) >= 0 || response.key.indexOf(key) >= 0)) {
this.delKey(response.key);
} else {
// this._log(`skip ${response.key}`)
}
}
}
len --;
if (len === 0) {
this.memcached.end();
let end = new Date();
this._log(`>>>>>> clean success in ${end.getTime() - begin.getTime()} , all keys: ${count}`)
}
})
})
})
});
}
_log(message) {
ws.broadcast(`/api_cache/log`, {
host: this.host,
msg: message
});
}
}
export default ApiCache;