cache.js
2.53 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
111
112
113
114
115
116
117
118
119
120
121
/**
* 缓存封装
* 前期使用 memcache, 写方法的时候考虑一下如何转换为 redis
* @author bikai kai.bi@yoho.cn
* @date 2016/05/16
*/
'use strict';
const Promise = require('bluebird');
const Memcached = require('memcached');
const _ = require('lodash');
const log = require('./logger');
const config = require('../config/common');
let master = new Memcached(config.memcache.master, config.memcache);
let slave = new Memcached(config.memcache.slave, config.memcache);
master = Promise.promisifyAll(master);
slave = Promise.promisifyAll(slave);
/**
* 获取缓存
* @param {[string]} key 键
* @return {[type]}
*/
exports.get = (key) => {
if (_.isString(key)) {
return master.getAsync(key);
}
return Promise.resolve();
};
/**
* 批量获取缓存
* @param {[array]} list 字符串数组
* @return {[type]}
*/
exports.getMulti = (list) => {
if (_.isArray(list)) {
return master.getMultiAsync(list);
}
return Promise.resolve();
};
/**
* 获取缓存(从 Slave 服务器)
* @param {[string]} key 键
* @return {[type]}
*/
exports.getFromSlave = (key) => {
if (_.isString(key)) {
return slave.getAsync(key);
}
return Promise.resolve();
};
/**
* 批量获取缓存(从 Slave 服务器)
* @param {[array]} list 字符串数组
* @return {[type]}
*/
exports.getMultiFromSlave = (list) => {
if (_.isArray(list)) {
return slave.getMultiAsync(list);
}
return Promise.resolve();
};
/**
* 写缓存
* @param {[type]} key 键
* @param {[type]} value 值
* @param {[type]} lifetime 生命周期
* @return {[type]}
*/
exports.set = (key, value, lifetime) => {
lifetime = lifetime || 86400;
log.info(`write cache: ${key}`);
if (_.isObject(value)) {
value = JSON.stringify(value);
}
if (_.isString(key)) {
return master.setAsync(key, value, lifetime);
}
return Promise.resolve();
};
/**
* 写缓存(到 Slave 服务器)
* @param {[type]} key 键
* @param {[type]} value 值
* @param {[type]} lifetime 生命周期
* @return {[type]}
*/
exports.setSlave = (key, value, lifetime) => {
lifetime = lifetime || 86400;
if (_.isObject(value)) {
value = JSON.stringify(value);
}
if (_.isString(key)) {
return slave.setAsync(key, value, lifetime);
}
return Promise.resolve();
};
/**
* 删除缓存
* @param {[string]} key 键
* @return {[type]}
*/
exports.del = (key) => {
if (_.isString(key)) {
return master.delAsync(key);
}
return Promise.resolve();
};