cache.js 2.46 KB
/**
 * 缓存封装
 * 前期使用 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 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;

    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();
};