51 lines
981 B
JavaScript
51 lines
981 B
JavaScript
const redis = require("redis");
|
|
const config = require("../../config/config");
|
|
let rclient = null;
|
|
module.exports = {
|
|
|
|
getConfig() {
|
|
let { port, host, opt } = config.redis || {}
|
|
return { port, host, opt }
|
|
},
|
|
init() {
|
|
|
|
let { port, host, opt } = this.getConfig()
|
|
|
|
if (host && port) {
|
|
rclient = redis.createClient(port, host, opt);
|
|
rclient.auth(config.pwd, function () {
|
|
console.log("redis通过认证");
|
|
});
|
|
rclient.on("connect", function () {
|
|
console.log("redis连接成功");
|
|
});
|
|
}
|
|
|
|
|
|
},
|
|
|
|
// 设置key值
|
|
set(key, value, expire = 0) {
|
|
if (!rclient) {
|
|
this.init();
|
|
}
|
|
|
|
rclient.set(key, value); //赋值
|
|
if (expire) {
|
|
rclient.expire(key, expire); //60秒自动过期
|
|
}
|
|
},
|
|
|
|
get(key) {
|
|
if (!rclient) {
|
|
this.init();
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
rclient.get(key, function (err, data) {
|
|
resolve(data);
|
|
});
|
|
});
|
|
},
|
|
};
|