繁体   English   中英

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

[英]Check if cache key exists using redis in node.js application with node_redis

我已经使用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];
    }
});

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

如果 redis 中存在,您可以使用这样的方式获取密钥

client.exists('photos', function (err, reply) {
  if (reply === 1) {
    console.log('exists');
    await client.get('photos');
    res.send(JSON.parse(reply));
    return;
  } else {
    console.log('doesn\'t exist');
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM