Skip to content

06 如何操作Redis

孙正华 edited this page Jul 26, 2018 · 3 revisions

Node.js 下可以使用 node_redis 客户端来操作 Redis.

安装 Redis

$ npm install --save redis

连接 Redis

https://github.com/eshengsky/iBlog2/blob/master/utility/redisClient.js#L7

var client = redis.createClient(config.redis.port || 6379, config.redis.host || 'localhost');

读取缓存

https://github.com/eshengsky/iBlog2/blob/master/utility/redisClient.js#L42-L53

/**
 * 获取缓存
 * @param key 缓存key
 * @param callback 回调函数
 */
exports.getItem = function (key, callback) {
    if (!redisEnable) {
        return callback(null, null);
    }

    client.get(key, function (err, reply) {
        if (err) {
            return callback(err);
        }
        return callback(null, JSON.parse(reply));
    });
};

写入缓存

https://github.com/eshengsky/iBlog2/blob/master/utility/redisClient.js#L21-L35

/**
 * 设置缓存
 * @param key 缓存key
 * @param value 缓存value
 * @param expired 缓存的有效时长,单位秒
 * @param callback 回调函数
 */
exports.setItem = function (key, value, expired, callback) {
    if (!redisEnable) {
        return callback(null);
    }

    client.set(key, JSON.stringify(value), function (err) {
        if (err) {
            return callback(err);
        }
        if (expired) {
            client.expire(key, expired);
        }
        return callback(null);
    });
};

删除缓存

https://github.com/eshengsky/iBlog2/blob/master/utility/redisClient.js#L60-L71

/**
 * 移除缓存
 * @param key 缓存key
 * @param callback 回调函数
 */
exports.removeItem = function (key, callback) {
    if (!redisEnable) {
        return callback(null);
    }

    client.del(key, function (err) {
        if (err) {
            return callback(err);
        }
        return callback(null);
    });
};

一个完整的例子

https://github.com/eshengsky/iBlog2/blob/master/proxy/category.js#L21-L55

// 缓存的key名称
const cache_key = 'categories';
if (cached) {
    // 尝试读取缓存
    redisClient.getItem(cache_key, (err, categories) => {
        // 读取缓存出错
        if (err) {
            return callback(err);
        }

        // 缓存中有数据
        if (categories) {
            return callback(null, categories);
        }

        // 缓存中没有数据,则从数据库中读取
        categoryModel.find((err, categories) => {
            // 读取数据库出错
            if (err) {
                return callback(err);
            }

            // 从数据库中读到数据
            if (categories) {
                // 将数据塞入缓存
                redisClient.setItem(cache_key, categories, redisClient.defaultExpired, err => {
                    if (err) {
                        return callback(err);
                    }
                });
            }
            return callback(null, categories);
        });
    });
}