redis.js 1.05 KB

const _ = require('lodash');
const redis = require('redis');
const bluebird = require('bluebird');
const config = require('../../config/common');
const logger = global.yoho.logger;
const timeout = 200; // redis 操作超时时间
let client;

try {
    client = redis.createClient(config.redis.connect);

    bluebird.promisifyAll(redis.RedisClient.prototype);
    bluebird.promisifyAll(redis.Multi.prototype);

    client.all = args => {
        if (!client.ready) {
            if (Array.isArray(args)) {
                return Promise.resolve(_.fill(args, false));
            } else {
                return Promise.resolve(false);
            }
        }

        return client.multi.call(client, args).execAsync().timeout(timeout).catch(()=>{
            logger.err('redis exe time out');
            return false;
        });
    };



    client.on('error', function() {
        global.yoho.redis = '';
    });

    client.on('connect', function() {
        global.yoho.redis = client;
    });
} catch (e) {
    global.yoho.redis = '';
}

module.exports = client;