48 lines
1.1 KiB
JavaScript
48 lines
1.1 KiB
JavaScript
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
|
|
*/
|
|
async setVal(key, val, expire = this._expire) {
|
|
return new Promise((resolve, reject) => {
|
|
this._conn.set(key, val, expire, err => {
|
|
if (err) return reject(err);
|
|
return resolve(null);
|
|
})
|
|
})
|
|
}
|
|
|
|
/**
|
|
* get object from memcached
|
|
* @param {string} key
|
|
*/
|
|
async getVal(key) {
|
|
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(); |