node.js with redis: synchronous or asynchronous?

2019-05-17 21:11发布

问题:

In my app (node / express / redis), I use some code to update several items in DB at the same time:

app.put('myaction', function(req, res){
    // delete stuff
    db.del("key1");
    db.srem("set1", "test");

    // Add stuff
    db.sadd("set2", "test2");
    db.sadd("set3", "test3");
    db.hmset("hash1", "k11", "v11", "k21", "v21");
    db.hmset("hash2", "k12", "v12", "k22", "v22");
    // ...

    // Send response back
    res.writeHead(200, {'content-type': 'application/json'});
    res.write(JSON.stringify({ "status" : "ok" }));

    res.end(); 
});

Can I be sure ALL those actions will be performed before the method returns ? My concern is the asynchronous processing. As I do not use callback function in the db actions, will this be alright ?

回答1:

Use the MULTI/EXEC command to create a queue of your commands and execute them in a row. Then use a callback to send a coherent response back (success/failure). Note that you must use Redis' AOF to avoid that - in case of crash - the db state is not coherent with your logic because only a part of the commands in the queue were executed: i.e. MULTI/EXEC is not transactional upon execution. This is a useful reference.



回答2:

While all of the commands are sent and responses parsed asynchronously, it's useful to note that the callbacks are all invoked in order. So you can use the callback of the last Redis command to send the response to the client, and then you'll know that all of the Redis commands have been executed before responding.



回答3:

I haven't worked with redis, but if this works(if you it doesn't call undefined function) and it should be asynchronous, then you can use it. But if there is an error in updating, then you can't handle it, this way.



回答4:

No, you can't be sure if all those actions complete successfully, because your redis server might crash.. To speed things up, you can group all your update commands into one with pipelining (does your redis driver support that?), then get the success or failure of the whole operation via a callback and proceed..



标签: node.js redis