简体   繁体   English

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

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

I have setup an application with node_redis , and I am trying to get the simple get/set to work.我已经使用node_redis设置了一个应用程序,并且我正在尝试让简单的 get/set 工作。

It seems I can insert into the cache, but I would like to be able to make a check if the key exists.看来我可以插入缓存,但我希望能够检查密钥是否存在。

In C# I would do something like: if(Cache["mykey"] == null) .在 C# 中,我会做类似的事情: if(Cache["mykey"] == null)

How do I make the check?我该如何做支票? What do I replace if(!client.get[cacheKey]) { with ?我用什么替换if(!client.get[cacheKey]) {

My code :我的代码

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

The most important thing to note here is that the redis client, like most other things in node, is not synchronous.这里需要注意的最重要的一点是,redis 客户端和 node 中的大多数其他东西一样,不是同步的。

The way you are accessing client.get implies it's an array in Javascript.您访问client.get的方式意味着它是 Javascript 中的一个数组。 It is really a function, like mongoose.find , that expects a callback as the last parameter.它实际上是一个函数,例如mongoose.find ,它期望回调作为最后一个参数。 In this case you just pass cacheKey first.在这种情况下,您只需先传递cacheKey Your if clause goes inside the callback.您的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 you have any code that followed your if-statement as if it was synchronous, it should most likely also go inside the callback function.如果您的 if 语句后面有任何代码,就好像它是同步的一样,它很可能也应该放在回调函数中。

you can use like that to get Keys if exist in redis如果 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