【问题标题】:Check if cache key exists using redis in node.js application with node_redis使用 node_redis 在 node.js 应用程序中使用 redis 检查缓存键是否存在
【发布时间】:2014-07-21 09:14:18
【问题描述】:

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

看来我可以插入缓存,但我希望能够检查密钥是否存在。

在 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];
    }
});

【问题讨论】:

    标签: node.js redis node-redis


    【解决方案1】:

    这里要注意的最重要的一点是,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 语句后面有任何代码,就好像它是同步的一样,它很可能也应该放在回调函数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2020-02-23
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多