简体   繁体   中英

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.

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) .

How do I make the check? What do I replace if(!client.get[cacheKey]) { with ?

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.

The way you are accessing client.get implies it's an array in Javascript. It is really a function, like mongoose.find , that expects a callback as the last parameter. In this case you just pass cacheKey first. Your if clause goes inside the callback.

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.

you can use like that to get Keys if exist in 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');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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