node.js - 使用 node_redis 在 node.js 应用程序中使用 redis 检查缓存键是否存在

标签 node.js redis node-redis

我已经使用 node_redis 设置了一个应用程序,我正在尝试让简单的 get/set 工作。

似乎我可以插入到缓存中,但我希望能够检查 key 是否存在。

在 C# 中,我会做类似这样的事情:if(Cache["mykey"] == null)

如何进行支票?我应该用 if(!client.get[cacheKey]) { 替换什么?

我的代码:

    app.get('/users',function(req,res) {
    var cacheKey = 'userKey';

    if(!client.get[cacheKey]) {
            mongoose.model('users').find(function(err,users) {
                console.log('Setting cache: ' + cacheKey);
                client.set(cacheKey,users,redis.print);
                res.send(users);
        });
    } else {
        console.log('Getting from cache: ' + cacheKey);
        return client.get[cacheKey];
    }
});

最佳答案

这里要注意的最重要的一点是,redis 客户端和 node 中的大多数其他东西一样,不是同步的。

您访问 client.get 的方式暗示它是 Javascript 中的一个数组。它实际上是一个函数,如 mongoose.find,期望回调作为最后一个参数。在这种情况下,您只需先传递 cacheKey。您的 if 子句在回调中。

client.get(cacheKey, function(err, data) {
    // data is null if the key doesn't exist
    if(err || data === null) {
        mongoose.model('users').find(function(err,users) {
            console.log('Setting cache: ' + cacheKey);
            client.set(cacheKey,users,redis.print);
            res.send(users);
        });
    } else {
        return data;
    }
});

如果您的 if 语句后面有任何代码,就好像它是同步的一样,它很可能也应该放在回调函数中。

关于node.js - 使用 node_redis 在 node.js 应用程序中使用 redis 检查缓存键是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861451/

相关文章:

php - 使用 php 和 redis

node.js - 基于 Node.js 事件循环关闭 Redis 连接

node.js - Node JS-MongoDB : use an opening connection

node.js - Nodejs错误: spawn ENOENT

Node.js 传出 Http 请求连接限制(不能建立超过五个的连接)

data-structures - 如何确定没有正在运行的作业或消费者进程退出

javascript - 在 Meteor 中使用 AutoForm 可编辑表格

Redis 命令获取发布/订阅的所有可用 channel ?

node.js - Node redis zadd键错误

Node.js redis promisify 与 .multi 或 .batch