覆盖Redis方法

时间:2017-04-30 08:07:54

标签: javascript node.js node-redis

我尝试在我的应用中添加一个选项,以便使用缓存进行切换。对于缓存,我正在使用Redis并为此制作简单的包装器。当我尝试覆盖redis.get方法时,问题就出现了,它只是不起作用或找不到this

'use strict';

const redis = require('redis');
const config = require('../config');

const REDIS_EMPTY_VALUE = 'NOT_EXIST';
const MINUTE = 60;

let client = redis.createClient({
    host: config.get('REDIS_HOST'),
    port: config.get('REDIS_PORT')
});

client.on("error", function (err) {
    logging.error('Redis Error: ' + err);
    throw new Error(err);
});

/**
 * Next are custom extensions for Redis module
 */
client.emptyValue = REDIS_EMPTY_VALUE;
client.minute = MINUTE;
client.setAndExprire = function(key, value, expire) {
    this.set(key, value);
    this.expire(key, expire);
};

// Here is the problem
client.get = function(key, cb) {
    if (config.get('disable-cache') === 'true') return cb(null, null);
    return client.get(key, cb);
}

module.exports = client;

1 个答案:

答案 0 :(得分:0)

由于您覆盖了client.get,因此client.get成为您定义的新函数。这样,你可以调用redis包附带的函数。您可以使用另一个对象(自定义)来调用redis函数,如下所示:

member(Y,Ys)
相关问题