2017-06-02 10:07:25 +00:00
|
|
|
const Memcached = require('memcached');
|
|
|
|
|
|
|
|
class memcachedLib {
|
|
|
|
constructor() {
|
|
|
|
this._host = ''
|
|
|
|
this._port = ''
|
|
|
|
this._expire = 86400
|
|
|
|
this._conn = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
connect() {
|
|
|
|
this._conn = new Memcached(`${this._host}:${this._port}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* set object to memcached
|
|
|
|
* @param {string} key
|
|
|
|
* @param {string} val
|
|
|
|
* @param {number} expire
|
|
|
|
*/
|
2017-06-05 06:41:32 +00:00
|
|
|
async setVal(key, val, expire = this._expire) {
|
2017-06-02 10:07:25 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2017-06-05 06:41:32 +00:00
|
|
|
this._conn.set(key, val, expire, err => {
|
2017-06-02 10:07:25 +00:00
|
|
|
if (err) return reject(err);
|
|
|
|
return resolve(null);
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* get object from memcached
|
|
|
|
* @param {string} key
|
|
|
|
*/
|
2017-06-05 06:41:32 +00:00
|
|
|
async getVal(key) {
|
2017-06-02 10:07:25 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this._conn.get(key, (err, data) => {
|
|
|
|
if (err) return reject(err);
|
|
|
|
return resolve(data);
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
set host(str) { this._host = str }
|
|
|
|
set port(str) { this._port = str }
|
|
|
|
set expire(str) { this._expire = str }
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = new memcachedLib();
|