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